diff --git a/.flake8 b/.flake8
index e58504e6..ed931638 100644
--- a/.flake8
+++ b/.flake8
@@ -16,11 +16,13 @@
# Generated by synthtool. DO NOT EDIT!
[flake8]
-ignore = E203, E266, E501, W503, F401, F821, F841, W291
+ignore = E203, E266, E501, W503
exclude =
# Exclude generated code.
**/proto/**
**/gapic/**
+ **/services/**
+ **/types/**
*_pb2.py
# Standard linting exemptions.
diff --git a/.gitignore b/.gitignore
index df79b144..b87e1ed5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,7 @@
dist
build
eggs
+.eggs
parts
bin
var
@@ -44,11 +45,12 @@ pip-log.txt
# Built documentation
docs/_build
-htmlcov
+bigquery/docs/generated
# Virtual environment
env/
coverage.xml
+sponge_log.xml
# System test environment variables.
system_tests/local_test_setup
diff --git a/.kokoro/samples/lint/common.cfg b/.kokoro/samples/lint/common.cfg
new file mode 100644
index 00000000..23462008
--- /dev/null
+++ b/.kokoro/samples/lint/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "lint"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-game-servers/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-game-servers/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/lint/continuous.cfg b/.kokoro/samples/lint/continuous.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/lint/continuous.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/lint/periodic.cfg b/.kokoro/samples/lint/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/lint/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/lint/presubmit.cfg b/.kokoro/samples/lint/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/lint/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg
new file mode 100644
index 00000000..2bcbe6e9
--- /dev/null
+++ b/.kokoro/samples/python3.6/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.6"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-game-servers/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-game-servers/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.6/continuous.cfg b/.kokoro/samples/python3.6/continuous.cfg
new file mode 100644
index 00000000..7218af14
--- /dev/null
+++ b/.kokoro/samples/python3.6/continuous.cfg
@@ -0,0 +1,7 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
+
diff --git a/.kokoro/samples/python3.6/periodic.cfg b/.kokoro/samples/python3.6/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/python3.6/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.6/presubmit.cfg b/.kokoro/samples/python3.6/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.6/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg
new file mode 100644
index 00000000..fd5fcd69
--- /dev/null
+++ b/.kokoro/samples/python3.7/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.7"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-game-servers/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-game-servers/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/continuous.cfg b/.kokoro/samples/python3.7/continuous.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.7/continuous.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/periodic.cfg b/.kokoro/samples/python3.7/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/python3.7/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/presubmit.cfg b/.kokoro/samples/python3.7/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.7/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg
new file mode 100644
index 00000000..31cd062b
--- /dev/null
+++ b/.kokoro/samples/python3.8/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.8"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-game-servers/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-game-servers/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/continuous.cfg b/.kokoro/samples/python3.8/continuous.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.8/continuous.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/periodic.cfg b/.kokoro/samples/python3.8/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/python3.8/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/presubmit.cfg b/.kokoro/samples/python3.8/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.8/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh
new file mode 100755
index 00000000..4be76015
--- /dev/null
+++ b/.kokoro/test-samples.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# 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.
+
+
+# `-e` enables the script to automatically fail when a command fails
+# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero
+set -eo pipefail
+# Enables `**` to include files nested inside sub-folders
+shopt -s globstar
+
+cd github/python-game-servers
+
+# Run periodic samples tests at latest release
+if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then
+ LATEST_RELEASE=$(git describe --abbrev=0 --tags)
+ git checkout $LATEST_RELEASE
+fi
+
+# Disable buffering, so that the logs stream through.
+export PYTHONUNBUFFERED=1
+
+# Debug: show build environment
+env | grep KOKORO
+
+# Install nox
+python3.6 -m pip install --upgrade --quiet nox
+
+# Use secrets acessor service account to get secrets
+if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then
+ gcloud auth activate-service-account \
+ --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \
+ --project="cloud-devrel-kokoro-resources"
+fi
+
+# This script will create 3 files:
+# - testing/test-env.sh
+# - testing/service-account.json
+# - testing/client-secrets.json
+./scripts/decrypt-secrets.sh
+
+source ./testing/test-env.sh
+export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json
+
+# For cloud-run session, we activate the service account for gcloud sdk.
+gcloud auth activate-service-account \
+ --key-file "${GOOGLE_APPLICATION_CREDENTIALS}"
+
+export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json
+
+echo -e "\n******************** TESTING PROJECTS ********************"
+
+# Switch to 'fail at end' to allow all tests to complete before exiting.
+set +e
+# Use RTN to return a non-zero value if the test fails.
+RTN=0
+ROOT=$(pwd)
+# Find all requirements.txt in the samples directory (may break on whitespace).
+for file in samples/**/requirements.txt; do
+ cd "$ROOT"
+ # Navigate to the project folder.
+ file=$(dirname "$file")
+ cd "$file"
+
+ echo "------------------------------------------------------------"
+ echo "- testing $file"
+ echo "------------------------------------------------------------"
+
+ # Use nox to execute the tests for the project.
+ python3.6 -m nox -s "$RUN_TESTS_SESSION"
+ EXIT=$?
+
+ # If this is a periodic build, send the test log to the Build Cop Bot.
+ # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/buildcop.
+ if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then
+ chmod +x $KOKORO_GFILE_DIR/linux_amd64/buildcop
+ $KOKORO_GFILE_DIR/linux_amd64/buildcop
+ fi
+
+ if [[ $EXIT -ne 0 ]]; then
+ RTN=1
+ echo -e "\n Testing failed: Nox returned a non-zero exit code. \n"
+ else
+ echo -e "\n Testing completed.\n"
+ fi
+
+done
+cd "$ROOT"
+
+# Workaround for Kokoro permissions issue: delete secrets
+rm testing/{test-env.sh,client-secrets.json,service-account.json}
+
+exit "$RTN"
\ No newline at end of file
diff --git a/MANIFEST.in b/MANIFEST.in
index 68855abc..e9e29d12 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -20,3 +20,6 @@ recursive-include google *.json *.proto
recursive-include tests *
global-exclude *.py[co]
global-exclude __pycache__
+
+# Exclude scripts for samples readmegen
+prune scripts/readme-gen
\ No newline at end of file
diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html
index 228529ef..6316a537 100644
--- a/docs/_templates/layout.html
+++ b/docs/_templates/layout.html
@@ -21,8 +21,8 @@
- On January 1, 2020 this library will no longer support Python 2 on the latest released version.
- Previously released library versions will continue to be available. For more information please
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version.
+ Library versions released prior to that date will continue to be available. For more information please
visit
Python 2 support on Google Cloud.
{% block body %} {% endblock %}
diff --git a/docs/conf.py b/docs/conf.py
index b7057ab2..cf544790 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -43,7 +43,7 @@
# autodoc/autosummary flags
autoclass_content = "both"
-autodoc_default_flags = ["members"]
+autodoc_default_options = {"members": True}
autosummary_generate = True
@@ -337,7 +337,7 @@
intersphinx_mapping = {
"python": ("http://python.readthedocs.org/en/latest/", None),
"google-auth": ("https://google-auth.readthedocs.io/en/stable", None),
- "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None),
+ "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,),
"grpc": ("https://grpc.io/grpc/python/", None),
}
diff --git a/docs/gaming_v1/services.rst b/docs/gaming_v1/services.rst
index c0e4aee2..8b09a196 100644
--- a/docs/gaming_v1/services.rst
+++ b/docs/gaming_v1/services.rst
@@ -1,6 +1,15 @@
-Client for Google Cloud Gaming API
-==================================
+Services for Google Cloud Gaming v1 API
+=======================================
-.. automodule:: google.cloud.gaming_v1
+.. automodule:: google.cloud.gaming_v1.services.game_server_clusters_service
+ :members:
+ :inherited-members:
+.. automodule:: google.cloud.gaming_v1.services.game_server_configs_service
+ :members:
+ :inherited-members:
+.. automodule:: google.cloud.gaming_v1.services.game_server_deployments_service
+ :members:
+ :inherited-members:
+.. automodule:: google.cloud.gaming_v1.services.realms_service
:members:
:inherited-members:
diff --git a/docs/gaming_v1/types.rst b/docs/gaming_v1/types.rst
index a5b77f49..0396ea47 100644
--- a/docs/gaming_v1/types.rst
+++ b/docs/gaming_v1/types.rst
@@ -1,5 +1,5 @@
-Types for Google Cloud Gaming API
-=================================
+Types for Google Cloud Gaming v1 API
+====================================
.. automodule:: google.cloud.gaming_v1.types
:members:
diff --git a/google/cloud/gaming/__init__.py b/google/cloud/gaming/__init__.py
index c79c992f..f8ef22a2 100644
--- a/google/cloud/gaming/__init__.py
+++ b/google/cloud/gaming/__init__.py
@@ -15,16 +15,27 @@
# limitations under the License.
#
-
+from google.cloud.gaming_v1.services.game_server_clusters_service.async_client import (
+ GameServerClustersServiceAsyncClient,
+)
from google.cloud.gaming_v1.services.game_server_clusters_service.client import (
GameServerClustersServiceClient,
)
+from google.cloud.gaming_v1.services.game_server_configs_service.async_client import (
+ GameServerConfigsServiceAsyncClient,
+)
from google.cloud.gaming_v1.services.game_server_configs_service.client import (
GameServerConfigsServiceClient,
)
+from google.cloud.gaming_v1.services.game_server_deployments_service.async_client import (
+ GameServerDeploymentsServiceAsyncClient,
+)
from google.cloud.gaming_v1.services.game_server_deployments_service.client import (
GameServerDeploymentsServiceClient,
)
+from google.cloud.gaming_v1.services.realms_service.async_client import (
+ RealmsServiceAsyncClient,
+)
from google.cloud.gaming_v1.services.realms_service.client import RealmsServiceClient
from google.cloud.gaming_v1.types.common import DeployedFleetDetails
from google.cloud.gaming_v1.types.common import LabelSelector
@@ -160,12 +171,15 @@
"FleetConfig",
"GameServerCluster",
"GameServerClusterConnectionInfo",
+ "GameServerClustersServiceAsyncClient",
"GameServerClustersServiceClient",
"GameServerConfig",
"GameServerConfigOverride",
+ "GameServerConfigsServiceAsyncClient",
"GameServerConfigsServiceClient",
"GameServerDeployment",
"GameServerDeploymentRollout",
+ "GameServerDeploymentsServiceAsyncClient",
"GameServerDeploymentsServiceClient",
"GetGameServerClusterRequest",
"GetGameServerConfigRequest",
@@ -196,6 +210,7 @@
"PreviewUpdateGameServerClusterResponse",
"Realm",
"RealmSelector",
+ "RealmsServiceAsyncClient",
"RealmsServiceClient",
"ScalingConfig",
"Schedule",
diff --git a/google/cloud/gaming_v1/__init__.py b/google/cloud/gaming_v1/__init__.py
index 2f594128..d565585b 100644
--- a/google/cloud/gaming_v1/__init__.py
+++ b/google/cloud/gaming_v1/__init__.py
@@ -15,7 +15,6 @@
# limitations under the License.
#
-
from .services.game_server_clusters_service import GameServerClustersServiceClient
from .services.game_server_configs_service import GameServerConfigsServiceClient
from .services.game_server_deployments_service import GameServerDeploymentsServiceClient
@@ -93,12 +92,12 @@
"FleetConfig",
"GameServerCluster",
"GameServerClusterConnectionInfo",
- "GameServerClustersServiceClient",
"GameServerConfig",
"GameServerConfigOverride",
"GameServerConfigsServiceClient",
"GameServerDeployment",
"GameServerDeploymentRollout",
+ "GameServerDeploymentsServiceClient",
"GetGameServerClusterRequest",
"GetGameServerConfigRequest",
"GetGameServerDeploymentRequest",
@@ -138,5 +137,5 @@
"UpdateGameServerDeploymentRequest",
"UpdateGameServerDeploymentRolloutRequest",
"UpdateRealmRequest",
- "GameServerDeploymentsServiceClient",
+ "GameServerClustersServiceClient",
)
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/__init__.py b/google/cloud/gaming_v1/services/game_server_clusters_service/__init__.py
index a3c22b72..965e452b 100644
--- a/google/cloud/gaming_v1/services/game_server_clusters_service/__init__.py
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/__init__.py
@@ -16,5 +16,9 @@
#
from .client import GameServerClustersServiceClient
+from .async_client import GameServerClustersServiceAsyncClient
-__all__ = ("GameServerClustersServiceClient",)
+__all__ = (
+ "GameServerClustersServiceClient",
+ "GameServerClustersServiceAsyncClient",
+)
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/async_client.py b/google/cloud/gaming_v1/services/game_server_clusters_service/async_client.py
new file mode 100644
index 00000000..dd014a19
--- /dev/null
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/async_client.py
@@ -0,0 +1,725 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections import OrderedDict
+import functools
+import re
+from typing import Dict, Sequence, Tuple, Type, Union
+import pkg_resources
+
+import google.api_core.client_options as ClientOptions # type: ignore
+from google.api_core import exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.auth import credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
+
+from google.api_core import operation
+from google.api_core import operation_async
+from google.cloud.gaming_v1.services.game_server_clusters_service import pagers
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import game_server_clusters
+from google.protobuf import empty_pb2 as empty # type: ignore
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+from .transports.base import GameServerClustersServiceTransport
+from .transports.grpc_asyncio import GameServerClustersServiceGrpcAsyncIOTransport
+from .client import GameServerClustersServiceClient
+
+
+class GameServerClustersServiceAsyncClient:
+ """The game server cluster maps to Kubernetes clusters running
+ Agones and is used to manage fleets within clusters.
+ """
+
+ _client: GameServerClustersServiceClient
+
+ DEFAULT_ENDPOINT = GameServerClustersServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = GameServerClustersServiceClient.DEFAULT_MTLS_ENDPOINT
+
+ game_server_cluster_path = staticmethod(
+ GameServerClustersServiceClient.game_server_cluster_path
+ )
+
+ from_service_account_file = (
+ GameServerClustersServiceClient.from_service_account_file
+ )
+ from_service_account_json = from_service_account_file
+
+ get_transport_class = functools.partial(
+ type(GameServerClustersServiceClient).get_transport_class,
+ type(GameServerClustersServiceClient),
+ )
+
+ def __init__(
+ self,
+ *,
+ credentials: credentials.Credentials = None,
+ transport: Union[str, GameServerClustersServiceTransport] = "grpc_asyncio",
+ client_options: ClientOptions = None,
+ ) -> None:
+ """Instantiate the game server clusters service client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, ~.GameServerClustersServiceTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+
+ self._client = GameServerClustersServiceClient(
+ credentials=credentials, transport=transport, client_options=client_options,
+ )
+
+ async def list_game_server_clusters(
+ self,
+ request: game_server_clusters.ListGameServerClustersRequest = None,
+ *,
+ parent: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListGameServerClustersAsyncPager:
+ r"""Lists game server clusters in a given project and
+ location.
+
+ Args:
+ request (:class:`~.game_server_clusters.ListGameServerClustersRequest`):
+ The request object. Request message for
+ GameServerClustersService.ListGameServerClusters.
+ parent (:class:`str`):
+ Required. The parent resource name.
+ Uses the form:
+ "projects/{project}/locations/{location}/realms/{realm}".
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.pagers.ListGameServerClustersAsyncPager:
+ Response message for
+ GameServerClustersService.ListGameServerClusters.
+ Iterating over this object will yield
+ results and resolve additional pages
+ automatically.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_clusters.ListGameServerClustersRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_game_server_clusters,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.ListGameServerClustersAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_game_server_cluster(
+ self,
+ request: game_server_clusters.GetGameServerClusterRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_clusters.GameServerCluster:
+ r"""Gets details of a single game server cluster.
+
+ Args:
+ request (:class:`~.game_server_clusters.GetGameServerClusterRequest`):
+ The request object. Request message for
+ GameServerClustersService.GetGameServerCluster.
+ name (:class:`str`):
+ Required. The name of the game server cluster to
+ retrieve. Uses the form:
+
+ ``projects/{project}/locations/{location}/realms/{realm-id}/gameServerClusters/{cluster}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_clusters.GameServerCluster:
+ A game server cluster resource.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_clusters.GetGameServerClusterRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_game_server_cluster,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def create_game_server_cluster(
+ self,
+ request: game_server_clusters.CreateGameServerClusterRequest = None,
+ *,
+ parent: str = None,
+ game_server_cluster: game_server_clusters.GameServerCluster = None,
+ game_server_cluster_id: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Creates a new game server cluster in a given project
+ and location.
+
+ Args:
+ request (:class:`~.game_server_clusters.CreateGameServerClusterRequest`):
+ The request object. Request message for
+ GameServerClustersService.CreateGameServerCluster.
+ parent (:class:`str`):
+ Required. The parent resource name. Uses the form:
+ ``projects/{project}/locations/{location}/realms/{realm-id}``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ game_server_cluster (:class:`~.game_server_clusters.GameServerCluster`):
+ Required. The game server cluster
+ resource to be created.
+ This corresponds to the ``game_server_cluster`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ game_server_cluster_id (:class:`str`):
+ Required. The ID of the game server
+ cluster resource to be created.
+ This corresponds to the ``game_server_cluster_id`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.game_server_clusters.GameServerCluster``: A
+ game server cluster resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any(
+ [parent, game_server_cluster, game_server_cluster_id]
+ ):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_clusters.CreateGameServerClusterRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if game_server_cluster is not None:
+ request.game_server_cluster = game_server_cluster
+ if game_server_cluster_id is not None:
+ request.game_server_cluster_id = game_server_cluster_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.create_game_server_cluster,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ game_server_clusters.GameServerCluster,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def preview_create_game_server_cluster(
+ self,
+ request: game_server_clusters.PreviewCreateGameServerClusterRequest = None,
+ *,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_clusters.PreviewCreateGameServerClusterResponse:
+ r"""Previews creation of a new game server cluster in a
+ given project and location.
+
+ Args:
+ request (:class:`~.game_server_clusters.PreviewCreateGameServerClusterRequest`):
+ The request object. Request message for
+ GameServerClustersService.PreviewCreateGameServerCluster.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_clusters.PreviewCreateGameServerClusterResponse:
+ Response message for
+ GameServerClustersService.PreviewCreateGameServerCluster.
+
+ """
+ # Create or coerce a protobuf request object.
+
+ request = game_server_clusters.PreviewCreateGameServerClusterRequest(request)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.preview_create_game_server_cluster,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def delete_game_server_cluster(
+ self,
+ request: game_server_clusters.DeleteGameServerClusterRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Deletes a single game server cluster.
+
+ Args:
+ request (:class:`~.game_server_clusters.DeleteGameServerClusterRequest`):
+ The request object. Request message for
+ GameServerClustersService.DeleteGameServerCluster.
+ name (:class:`str`):
+ Required. The name of the game server cluster to delete.
+ Uses the form:
+ ``projects/{project}/locations/{location}/gameServerClusters/{cluster}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_clusters.DeleteGameServerClusterRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.delete_game_server_cluster,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ empty.Empty,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def preview_delete_game_server_cluster(
+ self,
+ request: game_server_clusters.PreviewDeleteGameServerClusterRequest = None,
+ *,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_clusters.PreviewDeleteGameServerClusterResponse:
+ r"""Previews deletion of a single game server cluster.
+
+ Args:
+ request (:class:`~.game_server_clusters.PreviewDeleteGameServerClusterRequest`):
+ The request object. Request message for
+ GameServerClustersService.PreviewDeleteGameServerCluster.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_clusters.PreviewDeleteGameServerClusterResponse:
+ Response message for
+ GameServerClustersService.PreviewDeleteGameServerCluster.
+
+ """
+ # Create or coerce a protobuf request object.
+
+ request = game_server_clusters.PreviewDeleteGameServerClusterRequest(request)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.preview_delete_game_server_cluster,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def update_game_server_cluster(
+ self,
+ request: game_server_clusters.UpdateGameServerClusterRequest = None,
+ *,
+ game_server_cluster: game_server_clusters.GameServerCluster = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Patches a single game server cluster.
+
+ Args:
+ request (:class:`~.game_server_clusters.UpdateGameServerClusterRequest`):
+ The request object. Request message for
+ GameServerClustersService.UpdateGameServerCluster.
+ game_server_cluster (:class:`~.game_server_clusters.GameServerCluster`):
+ Required. The game server cluster to be updated. Only
+ fields specified in update_mask are updated.
+ This corresponds to the ``game_server_cluster`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Required. Mask of fields to update. At least one path
+ must be supplied in this field. For the ``FieldMask``
+ definition, see
+
+ https: //developers.google.com/protocol-buffers //
+ /docs/reference/google.protobuf#fieldmask
+ This corresponds to the ``update_mask`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.game_server_clusters.GameServerCluster``: A
+ game server cluster resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([game_server_cluster, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_clusters.UpdateGameServerClusterRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if game_server_cluster is not None:
+ request.game_server_cluster = game_server_cluster
+ if update_mask is not None:
+ request.update_mask = update_mask
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.update_game_server_cluster,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("game_server_cluster.name", request.game_server_cluster.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ game_server_clusters.GameServerCluster,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def preview_update_game_server_cluster(
+ self,
+ request: game_server_clusters.PreviewUpdateGameServerClusterRequest = None,
+ *,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_clusters.PreviewUpdateGameServerClusterResponse:
+ r"""Previews updating a GameServerCluster.
+
+ Args:
+ request (:class:`~.game_server_clusters.PreviewUpdateGameServerClusterRequest`):
+ The request object. Request message for
+ GameServerClustersService.UpdateGameServerCluster.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_clusters.PreviewUpdateGameServerClusterResponse:
+ Response message for
+ GameServerClustersService.PreviewUpdateGameServerCluster
+
+ """
+ # Create or coerce a protobuf request object.
+
+ request = game_server_clusters.PreviewUpdateGameServerClusterRequest(request)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.preview_update_game_server_cluster,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("game_server_cluster.name", request.game_server_cluster.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+
+try:
+ _client_info = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution(
+ "google-cloud-game-servers",
+ ).version,
+ )
+except pkg_resources.DistributionNotFound:
+ _client_info = gapic_v1.client_info.ClientInfo()
+
+
+__all__ = ("GameServerClustersServiceAsyncClient",)
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/client.py b/google/cloud/gaming_v1/services/game_server_clusters_service/client.py
index 73dea99c..941dbd25 100644
--- a/google/cloud/gaming_v1/services/game_server_clusters_service/client.py
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/client.py
@@ -16,6 +16,7 @@
#
from collections import OrderedDict
+import os
import re
from typing import Callable, Dict, Sequence, Tuple, Type, Union
import pkg_resources
@@ -25,17 +26,22 @@
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
+from google.auth.transport import mtls # type: ignore
+from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.api_core import operation
+from google.api_core import operation_async
from google.cloud.gaming_v1.services.game_server_clusters_service import pagers
from google.cloud.gaming_v1.types import common
from google.cloud.gaming_v1.types import game_server_clusters
+from google.protobuf import empty_pb2 as empty # type: ignore
from google.protobuf import field_mask_pb2 as field_mask # type: ignore
from google.protobuf import timestamp_pb2 as timestamp # type: ignore
from .transports.base import GameServerClustersServiceTransport
from .transports.grpc import GameServerClustersServiceGrpcTransport
+from .transports.grpc_asyncio import GameServerClustersServiceGrpcAsyncIOTransport
class GameServerClustersServiceClientMeta(type):
@@ -50,9 +56,10 @@ class GameServerClustersServiceClientMeta(type):
OrderedDict()
) # type: Dict[str, Type[GameServerClustersServiceTransport]]
_transport_registry["grpc"] = GameServerClustersServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = GameServerClustersServiceGrpcAsyncIOTransport
def get_transport_class(
- cls, label: str = None
+ cls, label: str = None,
) -> Type[GameServerClustersServiceTransport]:
"""Return an appropriate transport class.
@@ -133,11 +140,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@staticmethod
def game_server_cluster_path(
- project: str, location: str, realm: str, cluster: str
+ project: str, location: str, realm: str, cluster: str,
) -> str:
"""Return a fully-qualified game_server_cluster string."""
return "projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}".format(
- project=project, location=location, realm=realm, cluster=cluster
+ project=project, location=location, realm=realm, cluster=cluster,
)
@staticmethod
@@ -167,65 +174,74 @@ def __init__(
transport (Union[str, ~.GameServerClustersServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (ClientOptions): Custom options for the client.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
- default endpoint provided by the client.
- (2) If ``transport`` argument is None, ``client_options`` can be
- used to create a mutual TLS transport. If ``client_cert_source``
- is provided, mutual TLS transport will be created with the given
- ``api_endpoint`` or the default mTLS endpoint, and the client
- SSL credentials obtained from ``client_cert_source``.
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = ClientOptions.from_dict(client_options)
+ if client_options is None:
+ client_options = ClientOptions.ClientOptions()
+
+ if client_options.api_endpoint is None:
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never")
+ if use_mtls_env == "never":
+ client_options.api_endpoint = self.DEFAULT_ENDPOINT
+ elif use_mtls_env == "always":
+ client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ elif use_mtls_env == "auto":
+ has_client_cert_source = (
+ client_options.client_cert_source is not None
+ or mtls.has_default_client_cert_source()
+ )
+ client_options.api_endpoint = (
+ self.DEFAULT_MTLS_ENDPOINT
+ if has_client_cert_source
+ else self.DEFAULT_ENDPOINT
+ )
+ else:
+ raise MutualTLSChannelError(
+ "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always"
+ )
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, GameServerClustersServiceTransport):
# transport is a GameServerClustersServiceTransport instance.
- if credentials:
+ if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
+ if client_options.scopes:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its scopes directly."
+ )
self._transport = transport
- elif client_options is None or (
- client_options.api_endpoint is None
- and client_options.client_cert_source is None
- ):
- # Don't trigger mTLS if we get an empty ClientOptions.
+ else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
- credentials=credentials, host=self.DEFAULT_ENDPOINT
- )
- else:
- # We have a non-empty ClientOptions. If client_cert_source is
- # provided, trigger mTLS with user provided endpoint or the default
- # mTLS endpoint.
- if client_options.client_cert_source:
- api_mtls_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_MTLS_ENDPOINT
- )
- else:
- api_mtls_endpoint = None
-
- api_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_ENDPOINT
- )
-
- self._transport = GameServerClustersServiceGrpcTransport(
credentials=credentials,
- host=api_endpoint,
- api_mtls_endpoint=api_mtls_endpoint,
+ credentials_file=client_options.credentials_file,
+ host=client_options.api_endpoint,
+ scopes=client_options.scopes,
+ api_mtls_endpoint=client_options.api_endpoint,
client_cert_source=client_options.client_cert_source,
)
@@ -238,7 +254,7 @@ def list_game_server_clusters(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListGameServerClustersPager:
- r"""Lists Game Server Clusters in a given project and
+ r"""Lists game server clusters in a given project and
location.
Args:
@@ -300,12 +316,12 @@ def list_game_server_clusters(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListGameServerClustersPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -327,7 +343,7 @@ def get_game_server_cluster(
The request object. Request message for
GameServerClustersService.GetGameServerCluster.
name (:class:`str`):
- Required. The name of the Game Server Cluster to
+ Required. The name of the game server cluster to
retrieve. Uses the form:
``projects/{project}/locations/{location}/realms/{realm-id}/gameServerClusters/{cluster}``.
@@ -343,7 +359,7 @@ def get_game_server_cluster(
Returns:
~.game_server_clusters.GameServerCluster:
- A Game Server Cluster resource.
+ A game server cluster resource.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
@@ -377,7 +393,7 @@ def get_game_server_cluster(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -407,14 +423,14 @@ def create_game_server_cluster(
on the ``request`` instance; if ``request`` is provided, this
should not be set.
game_server_cluster (:class:`~.game_server_clusters.GameServerCluster`):
- Required. The Game Server Cluster
+ Required. The game server cluster
resource to be created.
This corresponds to the ``game_server_cluster`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
game_server_cluster_id (:class:`str`):
- Required. The ID of the Game Server
- Cluster resource to be created.
+ Required. The ID of the game server
+ cluster resource to be created.
This corresponds to the ``game_server_cluster_id`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -431,7 +447,7 @@ def create_game_server_cluster(
The result type for the operation will be
:class:``~.game_server_clusters.GameServerCluster``: A
- Game Server Cluster resource.
+ game server cluster resource.
"""
# Create or coerce a protobuf request object.
@@ -465,8 +481,14 @@ def create_game_server_cluster(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -519,8 +541,14 @@ def preview_create_game_server_cluster(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -541,7 +569,7 @@ def delete_game_server_cluster(
The request object. Request message for
GameServerClustersService.DeleteGameServerCluster.
name (:class:`str`):
- Required. The name of the Game Server Cluster to delete.
+ Required. The name of the game server cluster to delete.
Uses the form:
``projects/{project}/locations/{location}/gameServerClusters/{cluster}``.
This corresponds to the ``name`` field
@@ -559,8 +587,20 @@ def delete_game_server_cluster(
An object representing a long-running operation.
The result type for the operation will be
- :class:``~.game_server_clusters.GameServerCluster``: A
- Game Server Cluster resource.
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
"""
# Create or coerce a protobuf request object.
@@ -588,14 +628,20 @@ def delete_game_server_cluster(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
response,
self._transport.operations_client,
- game_server_clusters.GameServerCluster,
+ empty.Empty,
metadata_type=common.OperationMetadata,
)
@@ -641,8 +687,14 @@ def preview_delete_game_server_cluster(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -664,7 +716,7 @@ def update_game_server_cluster(
The request object. Request message for
GameServerClustersService.UpdateGameServerCluster.
game_server_cluster (:class:`~.game_server_clusters.GameServerCluster`):
- Required. The Game Server Cluster to be updated. Only
+ Required. The game server cluster to be updated. Only
fields specified in update_mask are updated.
This corresponds to the ``game_server_cluster`` field
on the ``request`` instance; if ``request`` is provided, this
@@ -692,7 +744,7 @@ def update_game_server_cluster(
The result type for the operation will be
:class:``~.game_server_clusters.GameServerCluster``: A
- Game Server Cluster resource.
+ game server cluster resource.
"""
# Create or coerce a protobuf request object.
@@ -722,8 +774,16 @@ def update_game_server_cluster(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("game_server_cluster.name", request.game_server_cluster.name),)
+ ),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -775,8 +835,16 @@ def preview_update_game_server_cluster(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("game_server_cluster.name", request.game_server_cluster.name),)
+ ),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -785,8 +853,8 @@ def preview_update_game_server_cluster(
try:
_client_info = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
- "google-cloud-game-servers"
- ).version
+ "google-cloud-game-servers",
+ ).version,
)
except pkg_resources.DistributionNotFound:
_client_info = gapic_v1.client_info.ClientInfo()
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/pagers.py b/google/cloud/gaming_v1/services/game_server_clusters_service/pagers.py
index 310f3363..b2487187 100644
--- a/google/cloud/gaming_v1/services/game_server_clusters_service/pagers.py
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/pagers.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-from typing import Any, Callable, Iterable
+from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
from google.cloud.gaming_v1.types import game_server_clusters
@@ -40,12 +40,11 @@ class ListGameServerClustersPager:
def __init__(
self,
- method: Callable[
- [game_server_clusters.ListGameServerClustersRequest],
- game_server_clusters.ListGameServerClustersResponse,
- ],
+ method: Callable[..., game_server_clusters.ListGameServerClustersResponse],
request: game_server_clusters.ListGameServerClustersRequest,
response: game_server_clusters.ListGameServerClustersResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -56,10 +55,13 @@ def __init__(
The initial request object.
response (:class:`~.game_server_clusters.ListGameServerClustersResponse`):
The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
"""
self._method = method
self._request = game_server_clusters.ListGameServerClustersRequest(request)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@@ -69,7 +71,7 @@ def pages(self) -> Iterable[game_server_clusters.ListGameServerClustersResponse]
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[game_server_clusters.GameServerCluster]:
@@ -78,3 +80,73 @@ def __iter__(self) -> Iterable[game_server_clusters.GameServerCluster]:
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class ListGameServerClustersAsyncPager:
+ """A pager for iterating through ``list_game_server_clusters`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.game_server_clusters.ListGameServerClustersResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``game_server_clusters`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListGameServerClusters`` requests and continue to iterate
+ through the ``game_server_clusters`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.game_server_clusters.ListGameServerClustersResponse`
+ attributes are available on the pager. If multiple requests are made, only
+ the most recent response is retained, and thus used for attribute lookup.
+ """
+
+ def __init__(
+ self,
+ method: Callable[
+ ..., Awaitable[game_server_clusters.ListGameServerClustersResponse]
+ ],
+ request: game_server_clusters.ListGameServerClustersRequest,
+ response: game_server_clusters.ListGameServerClustersResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.game_server_clusters.ListGameServerClustersRequest`):
+ The initial request object.
+ response (:class:`~.game_server_clusters.ListGameServerClustersResponse`):
+ The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ self._method = method
+ self._request = game_server_clusters.ListGameServerClustersRequest(request)
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(
+ self,
+ ) -> AsyncIterable[game_server_clusters.ListGameServerClustersResponse]:
+ yield self._response
+ while self._response.next_page_token:
+ self._request.page_token = self._response.next_page_token
+ self._response = await self._method(self._request, metadata=self._metadata)
+ yield self._response
+
+ def __aiter__(self) -> AsyncIterable[game_server_clusters.GameServerCluster]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.game_server_clusters:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/transports/__init__.py b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/__init__.py
index 6e118b97..ce769656 100644
--- a/google/cloud/gaming_v1/services/game_server_clusters_service/transports/__init__.py
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/__init__.py
@@ -20,6 +20,7 @@
from .base import GameServerClustersServiceTransport
from .grpc import GameServerClustersServiceGrpcTransport
+from .grpc_asyncio import GameServerClustersServiceGrpcAsyncIOTransport
# Compile a registry of transports.
@@ -27,9 +28,11 @@
OrderedDict()
) # type: Dict[str, Type[GameServerClustersServiceTransport]]
_transport_registry["grpc"] = GameServerClustersServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = GameServerClustersServiceGrpcAsyncIOTransport
__all__ = (
"GameServerClustersServiceTransport",
"GameServerClustersServiceGrpcTransport",
+ "GameServerClustersServiceGrpcAsyncIOTransport",
)
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/transports/base.py b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/base.py
index 6646a3bb..6da4c579 100644
--- a/google/cloud/gaming_v1/services/game_server_clusters_service/transports/base.py
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/base.py
@@ -19,6 +19,7 @@
import typing
from google import auth
+from google.api_core import exceptions # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.auth import credentials # type: ignore
@@ -26,7 +27,7 @@
from google.longrunning import operations_pb2 as operations # type: ignore
-class GameServerClustersServiceTransport(metaclass=abc.ABCMeta):
+class GameServerClustersServiceTransport(abc.ABC):
"""Abstract transport class for GameServerClustersService."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
@@ -36,6 +37,9 @@ def __init__(
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: typing.Optional[str] = None,
+ scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
+ **kwargs,
) -> None:
"""Instantiate the transport.
@@ -46,6 +50,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scope (Optional[Sequence[str]]): A list of scopes.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
@@ -54,8 +62,17 @@ def __init__(
# If no credentials are provided, then determine the appropriate
# defaults.
- if credentials is None:
- credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+ if credentials and credentials_file:
+ raise exceptions.DuplicateCredentialArgs(
+ "'credentials_file' and 'credentials' are mutually exclusive"
+ )
+
+ if credentials_file is not None:
+ credentials, _ = auth.load_credentials_from_file(
+ credentials_file, scopes=scopes
+ )
+ elif credentials is None:
+ credentials, _ = auth.default(scopes=scopes)
# Save the credentials.
self._credentials = credentials
@@ -63,76 +80,100 @@ def __init__(
@property
def operations_client(self) -> operations_v1.OperationsClient:
"""Return the client designed to process long-running operations."""
- raise NotImplementedError
+ raise NotImplementedError()
@property
def list_game_server_clusters(
- self
+ self,
) -> typing.Callable[
[game_server_clusters.ListGameServerClustersRequest],
- game_server_clusters.ListGameServerClustersResponse,
+ typing.Union[
+ game_server_clusters.ListGameServerClustersResponse,
+ typing.Awaitable[game_server_clusters.ListGameServerClustersResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def get_game_server_cluster(
- self
+ self,
) -> typing.Callable[
[game_server_clusters.GetGameServerClusterRequest],
- game_server_clusters.GameServerCluster,
+ typing.Union[
+ game_server_clusters.GameServerCluster,
+ typing.Awaitable[game_server_clusters.GameServerCluster],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def create_game_server_cluster(
- self
+ self,
) -> typing.Callable[
- [game_server_clusters.CreateGameServerClusterRequest], operations.Operation
+ [game_server_clusters.CreateGameServerClusterRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def preview_create_game_server_cluster(
- self
+ self,
) -> typing.Callable[
[game_server_clusters.PreviewCreateGameServerClusterRequest],
- game_server_clusters.PreviewCreateGameServerClusterResponse,
+ typing.Union[
+ game_server_clusters.PreviewCreateGameServerClusterResponse,
+ typing.Awaitable[
+ game_server_clusters.PreviewCreateGameServerClusterResponse
+ ],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def delete_game_server_cluster(
- self
+ self,
) -> typing.Callable[
- [game_server_clusters.DeleteGameServerClusterRequest], operations.Operation
+ [game_server_clusters.DeleteGameServerClusterRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def preview_delete_game_server_cluster(
- self
+ self,
) -> typing.Callable[
[game_server_clusters.PreviewDeleteGameServerClusterRequest],
- game_server_clusters.PreviewDeleteGameServerClusterResponse,
+ typing.Union[
+ game_server_clusters.PreviewDeleteGameServerClusterResponse,
+ typing.Awaitable[
+ game_server_clusters.PreviewDeleteGameServerClusterResponse
+ ],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def update_game_server_cluster(
- self
+ self,
) -> typing.Callable[
- [game_server_clusters.UpdateGameServerClusterRequest], operations.Operation
+ [game_server_clusters.UpdateGameServerClusterRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def preview_update_game_server_cluster(
- self
+ self,
) -> typing.Callable[
[game_server_clusters.PreviewUpdateGameServerClusterRequest],
- game_server_clusters.PreviewUpdateGameServerClusterResponse,
+ typing.Union[
+ game_server_clusters.PreviewUpdateGameServerClusterResponse,
+ typing.Awaitable[
+ game_server_clusters.PreviewUpdateGameServerClusterResponse
+ ],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
__all__ = ("GameServerClustersServiceTransport",)
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/transports/grpc.py b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/grpc.py
index 5b9ab2a9..7c230e10 100644
--- a/google/cloud/gaming_v1/services/game_server_clusters_service/transports/grpc.py
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/grpc.py
@@ -15,10 +15,11 @@
# limitations under the License.
#
-from typing import Callable, Dict, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
+from google import auth # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
@@ -45,11 +46,15 @@ class GameServerClustersServiceGrpcTransport(GameServerClustersServiceTransport)
top of HTTP/2); the ``grpcio`` package must be installed.
"""
+ _stubs: Dict[str, Callable]
+
def __init__(
self,
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
@@ -64,6 +69,11 @@ def __init__(
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
+ ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
@@ -76,8 +86,10 @@ def __init__(
is None.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
if channel:
# Sanity check: Ensure that channel and credentials are not both
@@ -93,6 +105,9 @@ def __init__(
else api_mtls_endpoint + ":443"
)
+ if credentials is None:
+ credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
@@ -104,15 +119,22 @@ def __init__(
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
- self._grpc_channel = grpc_helpers.create_channel(
+ self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
+ credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
- scopes=self.AUTH_SCOPES,
+ scopes=scopes or self.AUTH_SCOPES,
)
# Run the base constructor.
- super().__init__(host=host, credentials=credentials)
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
self._stubs = {} # type: Dict[str, Callable]
@classmethod
@@ -120,6 +142,8 @@ def create_channel(
cls,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Optional[Sequence[str]] = None,
**kwargs
) -> grpc.Channel:
"""Create and return a gRPC channel object.
@@ -130,13 +154,28 @@ def create_channel(
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
+
+ Raises:
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
+ scopes = scopes or cls.AUTH_SCOPES
return grpc_helpers.create_channel(
- host, credentials=credentials, scopes=cls.AUTH_SCOPES, **kwargs
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
)
@property
@@ -150,7 +189,7 @@ def grpc_channel(self) -> grpc.Channel:
# have one.
if not hasattr(self, "_grpc_channel"):
self._grpc_channel = self.create_channel(
- self._host, credentials=self._credentials
+ self._host, credentials=self._credentials,
)
# Return the channel from cache.
@@ -174,14 +213,14 @@ def operations_client(self) -> operations_v1.OperationsClient:
@property
def list_game_server_clusters(
- self
+ self,
) -> Callable[
[game_server_clusters.ListGameServerClustersRequest],
game_server_clusters.ListGameServerClustersResponse,
]:
r"""Return a callable for the list game server clusters method over gRPC.
- Lists Game Server Clusters in a given project and
+ Lists game server clusters in a given project and
location.
Returns:
@@ -204,7 +243,7 @@ def list_game_server_clusters(
@property
def get_game_server_cluster(
- self
+ self,
) -> Callable[
[game_server_clusters.GetGameServerClusterRequest],
game_server_clusters.GameServerCluster,
@@ -233,7 +272,7 @@ def get_game_server_cluster(
@property
def create_game_server_cluster(
- self
+ self,
) -> Callable[
[game_server_clusters.CreateGameServerClusterRequest], operations.Operation
]:
@@ -262,7 +301,7 @@ def create_game_server_cluster(
@property
def preview_create_game_server_cluster(
- self
+ self,
) -> Callable[
[game_server_clusters.PreviewCreateGameServerClusterRequest],
game_server_clusters.PreviewCreateGameServerClusterResponse,
@@ -295,7 +334,7 @@ def preview_create_game_server_cluster(
@property
def delete_game_server_cluster(
- self
+ self,
) -> Callable[
[game_server_clusters.DeleteGameServerClusterRequest], operations.Operation
]:
@@ -323,7 +362,7 @@ def delete_game_server_cluster(
@property
def preview_delete_game_server_cluster(
- self
+ self,
) -> Callable[
[game_server_clusters.PreviewDeleteGameServerClusterRequest],
game_server_clusters.PreviewDeleteGameServerClusterResponse,
@@ -355,7 +394,7 @@ def preview_delete_game_server_cluster(
@property
def update_game_server_cluster(
- self
+ self,
) -> Callable[
[game_server_clusters.UpdateGameServerClusterRequest], operations.Operation
]:
@@ -383,7 +422,7 @@ def update_game_server_cluster(
@property
def preview_update_game_server_cluster(
- self
+ self,
) -> Callable[
[game_server_clusters.PreviewUpdateGameServerClusterRequest],
game_server_clusters.PreviewUpdateGameServerClusterResponse,
diff --git a/google/cloud/gaming_v1/services/game_server_clusters_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/grpc_asyncio.py
new file mode 100644
index 00000000..bc9b7a78
--- /dev/null
+++ b/google/cloud/gaming_v1/services/game_server_clusters_service/transports/grpc_asyncio.py
@@ -0,0 +1,454 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+
+from google.api_core import grpc_helpers_async # type: ignore
+from google.api_core import operations_v1 # type: ignore
+from google.auth import credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+
+import grpc # type: ignore
+from grpc.experimental import aio # type: ignore
+
+from google.cloud.gaming_v1.types import game_server_clusters
+from google.longrunning import operations_pb2 as operations # type: ignore
+
+from .base import GameServerClustersServiceTransport
+from .grpc import GameServerClustersServiceGrpcTransport
+
+
+class GameServerClustersServiceGrpcAsyncIOTransport(GameServerClustersServiceTransport):
+ """gRPC AsyncIO backend transport for GameServerClustersService.
+
+ The game server cluster maps to Kubernetes clusters running
+ Agones and is used to manage fleets within clusters.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends protocol buffers over the wire using gRPC (which is built on
+ top of HTTP/2); the ``grpcio`` package must be installed.
+ """
+
+ _grpc_channel: aio.Channel
+ _stubs: Dict[str, Callable] = {}
+
+ @classmethod
+ def create_channel(
+ cls,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ **kwargs
+ ) -> aio.Channel:
+ """Create and return a gRPC AsyncIO channel object.
+ Args:
+ address (Optional[str]): The host for the channel to use.
+ credentials (Optional[~.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify this application to the service. If
+ none are specified, the client will attempt to ascertain
+ the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
+ channel creation.
+ Returns:
+ aio.Channel: A gRPC AsyncIO channel object.
+ """
+ scopes = scopes or cls.AUTH_SCOPES
+ return grpc_helpers_async.create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
+ )
+
+ def __init__(
+ self,
+ *,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ channel: aio.Channel = None,
+ api_mtls_endpoint: str = None,
+ client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]): The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ channel (Optional[aio.Channel]): A ``Channel`` instance through
+ which to make calls.
+ api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
+ provided, it overrides the ``host`` argument and tries to create
+ a mutual TLS channel with client SSL credentials from
+ ``client_cert_source`` or applicatin default SSL credentials.
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
+ callback to provide client SSL certificate bytes and private key
+ bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
+ is None.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
+ """
+ if channel:
+ # Sanity check: Ensure that channel and credentials are not both
+ # provided.
+ credentials = False
+
+ # If a channel was explicitly provided, set it.
+ self._grpc_channel = channel
+ elif api_mtls_endpoint:
+ host = (
+ api_mtls_endpoint
+ if ":" in api_mtls_endpoint
+ else api_mtls_endpoint + ":443"
+ )
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ ssl_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ ssl_credentials = SslCredentials().ssl_credentials
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ # Run the base constructor.
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ self._stubs = {}
+
+ @property
+ def grpc_channel(self) -> aio.Channel:
+ """Create the channel designed to connect to this service.
+
+ This property caches on the instance; repeated calls return
+ the same channel.
+ """
+ # Sanity check: Only create a new channel if we do not already
+ # have one.
+ if not hasattr(self, "_grpc_channel"):
+ self._grpc_channel = self.create_channel(
+ self._host, credentials=self._credentials,
+ )
+
+ # Return the channel from cache.
+ return self._grpc_channel
+
+ @property
+ def operations_client(self) -> operations_v1.OperationsAsyncClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Sanity check: Only create a new client if we do not already have one.
+ if "operations_client" not in self.__dict__:
+ self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient(
+ self.grpc_channel
+ )
+
+ # Return the client from cache.
+ return self.__dict__["operations_client"]
+
+ @property
+ def list_game_server_clusters(
+ self,
+ ) -> Callable[
+ [game_server_clusters.ListGameServerClustersRequest],
+ Awaitable[game_server_clusters.ListGameServerClustersResponse],
+ ]:
+ r"""Return a callable for the list game server clusters method over gRPC.
+
+ Lists game server clusters in a given project and
+ location.
+
+ Returns:
+ Callable[[~.ListGameServerClustersRequest],
+ Awaitable[~.ListGameServerClustersResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "list_game_server_clusters" not in self._stubs:
+ self._stubs["list_game_server_clusters"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/ListGameServerClusters",
+ request_serializer=game_server_clusters.ListGameServerClustersRequest.serialize,
+ response_deserializer=game_server_clusters.ListGameServerClustersResponse.deserialize,
+ )
+ return self._stubs["list_game_server_clusters"]
+
+ @property
+ def get_game_server_cluster(
+ self,
+ ) -> Callable[
+ [game_server_clusters.GetGameServerClusterRequest],
+ Awaitable[game_server_clusters.GameServerCluster],
+ ]:
+ r"""Return a callable for the get game server cluster method over gRPC.
+
+ Gets details of a single game server cluster.
+
+ Returns:
+ Callable[[~.GetGameServerClusterRequest],
+ Awaitable[~.GameServerCluster]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_game_server_cluster" not in self._stubs:
+ self._stubs["get_game_server_cluster"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/GetGameServerCluster",
+ request_serializer=game_server_clusters.GetGameServerClusterRequest.serialize,
+ response_deserializer=game_server_clusters.GameServerCluster.deserialize,
+ )
+ return self._stubs["get_game_server_cluster"]
+
+ @property
+ def create_game_server_cluster(
+ self,
+ ) -> Callable[
+ [game_server_clusters.CreateGameServerClusterRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the create game server cluster method over gRPC.
+
+ Creates a new game server cluster in a given project
+ and location.
+
+ Returns:
+ Callable[[~.CreateGameServerClusterRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "create_game_server_cluster" not in self._stubs:
+ self._stubs["create_game_server_cluster"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/CreateGameServerCluster",
+ request_serializer=game_server_clusters.CreateGameServerClusterRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["create_game_server_cluster"]
+
+ @property
+ def preview_create_game_server_cluster(
+ self,
+ ) -> Callable[
+ [game_server_clusters.PreviewCreateGameServerClusterRequest],
+ Awaitable[game_server_clusters.PreviewCreateGameServerClusterResponse],
+ ]:
+ r"""Return a callable for the preview create game server
+ cluster method over gRPC.
+
+ Previews creation of a new game server cluster in a
+ given project and location.
+
+ Returns:
+ Callable[[~.PreviewCreateGameServerClusterRequest],
+ Awaitable[~.PreviewCreateGameServerClusterResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "preview_create_game_server_cluster" not in self._stubs:
+ self._stubs[
+ "preview_create_game_server_cluster"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewCreateGameServerCluster",
+ request_serializer=game_server_clusters.PreviewCreateGameServerClusterRequest.serialize,
+ response_deserializer=game_server_clusters.PreviewCreateGameServerClusterResponse.deserialize,
+ )
+ return self._stubs["preview_create_game_server_cluster"]
+
+ @property
+ def delete_game_server_cluster(
+ self,
+ ) -> Callable[
+ [game_server_clusters.DeleteGameServerClusterRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the delete game server cluster method over gRPC.
+
+ Deletes a single game server cluster.
+
+ Returns:
+ Callable[[~.DeleteGameServerClusterRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_game_server_cluster" not in self._stubs:
+ self._stubs["delete_game_server_cluster"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/DeleteGameServerCluster",
+ request_serializer=game_server_clusters.DeleteGameServerClusterRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["delete_game_server_cluster"]
+
+ @property
+ def preview_delete_game_server_cluster(
+ self,
+ ) -> Callable[
+ [game_server_clusters.PreviewDeleteGameServerClusterRequest],
+ Awaitable[game_server_clusters.PreviewDeleteGameServerClusterResponse],
+ ]:
+ r"""Return a callable for the preview delete game server
+ cluster method over gRPC.
+
+ Previews deletion of a single game server cluster.
+
+ Returns:
+ Callable[[~.PreviewDeleteGameServerClusterRequest],
+ Awaitable[~.PreviewDeleteGameServerClusterResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "preview_delete_game_server_cluster" not in self._stubs:
+ self._stubs[
+ "preview_delete_game_server_cluster"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewDeleteGameServerCluster",
+ request_serializer=game_server_clusters.PreviewDeleteGameServerClusterRequest.serialize,
+ response_deserializer=game_server_clusters.PreviewDeleteGameServerClusterResponse.deserialize,
+ )
+ return self._stubs["preview_delete_game_server_cluster"]
+
+ @property
+ def update_game_server_cluster(
+ self,
+ ) -> Callable[
+ [game_server_clusters.UpdateGameServerClusterRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the update game server cluster method over gRPC.
+
+ Patches a single game server cluster.
+
+ Returns:
+ Callable[[~.UpdateGameServerClusterRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "update_game_server_cluster" not in self._stubs:
+ self._stubs["update_game_server_cluster"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/UpdateGameServerCluster",
+ request_serializer=game_server_clusters.UpdateGameServerClusterRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["update_game_server_cluster"]
+
+ @property
+ def preview_update_game_server_cluster(
+ self,
+ ) -> Callable[
+ [game_server_clusters.PreviewUpdateGameServerClusterRequest],
+ Awaitable[game_server_clusters.PreviewUpdateGameServerClusterResponse],
+ ]:
+ r"""Return a callable for the preview update game server
+ cluster method over gRPC.
+
+ Previews updating a GameServerCluster.
+
+ Returns:
+ Callable[[~.PreviewUpdateGameServerClusterRequest],
+ Awaitable[~.PreviewUpdateGameServerClusterResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "preview_update_game_server_cluster" not in self._stubs:
+ self._stubs[
+ "preview_update_game_server_cluster"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewUpdateGameServerCluster",
+ request_serializer=game_server_clusters.PreviewUpdateGameServerClusterRequest.serialize,
+ response_deserializer=game_server_clusters.PreviewUpdateGameServerClusterResponse.deserialize,
+ )
+ return self._stubs["preview_update_game_server_cluster"]
+
+
+__all__ = ("GameServerClustersServiceGrpcAsyncIOTransport",)
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/__init__.py b/google/cloud/gaming_v1/services/game_server_configs_service/__init__.py
index fb3b973f..a805cae2 100644
--- a/google/cloud/gaming_v1/services/game_server_configs_service/__init__.py
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/__init__.py
@@ -16,5 +16,9 @@
#
from .client import GameServerConfigsServiceClient
+from .async_client import GameServerConfigsServiceAsyncClient
-__all__ = ("GameServerConfigsServiceClient",)
+__all__ = (
+ "GameServerConfigsServiceClient",
+ "GameServerConfigsServiceAsyncClient",
+)
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/async_client.py b/google/cloud/gaming_v1/services/game_server_configs_service/async_client.py
new file mode 100644
index 00000000..f36e03da
--- /dev/null
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/async_client.py
@@ -0,0 +1,465 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections import OrderedDict
+import functools
+import re
+from typing import Dict, Sequence, Tuple, Type, Union
+import pkg_resources
+
+import google.api_core.client_options as ClientOptions # type: ignore
+from google.api_core import exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.auth import credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
+
+from google.api_core import operation
+from google.api_core import operation_async
+from google.cloud.gaming_v1.services.game_server_configs_service import pagers
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import game_server_configs
+from google.protobuf import empty_pb2 as empty # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+from .transports.base import GameServerConfigsServiceTransport
+from .transports.grpc_asyncio import GameServerConfigsServiceGrpcAsyncIOTransport
+from .client import GameServerConfigsServiceClient
+
+
+class GameServerConfigsServiceAsyncClient:
+ """The game server config configures the game servers in an
+ Agones fleet.
+ """
+
+ _client: GameServerConfigsServiceClient
+
+ DEFAULT_ENDPOINT = GameServerConfigsServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = GameServerConfigsServiceClient.DEFAULT_MTLS_ENDPOINT
+
+ game_server_config_path = staticmethod(
+ GameServerConfigsServiceClient.game_server_config_path
+ )
+
+ from_service_account_file = GameServerConfigsServiceClient.from_service_account_file
+ from_service_account_json = from_service_account_file
+
+ get_transport_class = functools.partial(
+ type(GameServerConfigsServiceClient).get_transport_class,
+ type(GameServerConfigsServiceClient),
+ )
+
+ def __init__(
+ self,
+ *,
+ credentials: credentials.Credentials = None,
+ transport: Union[str, GameServerConfigsServiceTransport] = "grpc_asyncio",
+ client_options: ClientOptions = None,
+ ) -> None:
+ """Instantiate the game server configs service client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, ~.GameServerConfigsServiceTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+
+ self._client = GameServerConfigsServiceClient(
+ credentials=credentials, transport=transport, client_options=client_options,
+ )
+
+ async def list_game_server_configs(
+ self,
+ request: game_server_configs.ListGameServerConfigsRequest = None,
+ *,
+ parent: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListGameServerConfigsAsyncPager:
+ r"""Lists game server configs in a given project,
+ location, and game server deployment.
+
+ Args:
+ request (:class:`~.game_server_configs.ListGameServerConfigsRequest`):
+ The request object. Request message for
+ GameServerConfigsService.ListGameServerConfigs.
+ parent (:class:`str`):
+ Required. The parent resource name. Uses the form:
+
+ ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/*``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.pagers.ListGameServerConfigsAsyncPager:
+ Response message for
+ GameServerConfigsService.ListGameServerConfigs.
+ Iterating over this object will yield
+ results and resolve additional pages
+ automatically.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_configs.ListGameServerConfigsRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_game_server_configs,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.ListGameServerConfigsAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_game_server_config(
+ self,
+ request: game_server_configs.GetGameServerConfigRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_configs.GameServerConfig:
+ r"""Gets details of a single game server config.
+
+ Args:
+ request (:class:`~.game_server_configs.GetGameServerConfigRequest`):
+ The request object. Request message for
+ GameServerConfigsService.GetGameServerConfig.
+ name (:class:`str`):
+ Required. The name of the game server config to
+ retrieve. Uses the form:
+
+ ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_configs.GameServerConfig:
+ A game server config resource.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_configs.GetGameServerConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_game_server_config,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def create_game_server_config(
+ self,
+ request: game_server_configs.CreateGameServerConfigRequest = None,
+ *,
+ parent: str = None,
+ game_server_config: game_server_configs.GameServerConfig = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Creates a new game server config in a given project,
+ location, and game server deployment. Game server
+ configs are immutable, and are not applied until
+ referenced in the game server deployment rollout
+ resource.
+
+ Args:
+ request (:class:`~.game_server_configs.CreateGameServerConfigRequest`):
+ The request object. Request message for
+ GameServerConfigsService.CreateGameServerConfig.
+ parent (:class:`str`):
+ Required. The parent resource name. Uses the form:
+
+ ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ game_server_config (:class:`~.game_server_configs.GameServerConfig`):
+ Required. The game server config
+ resource to be created.
+ This corresponds to the ``game_server_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.game_server_configs.GameServerConfig``: A
+ game server config resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent, game_server_config]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_configs.CreateGameServerConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if game_server_config is not None:
+ request.game_server_config = game_server_config
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.create_game_server_config,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ game_server_configs.GameServerConfig,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def delete_game_server_config(
+ self,
+ request: game_server_configs.DeleteGameServerConfigRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Deletes a single game server config. The deletion
+ will fail if the game server config is referenced in a
+ game server deployment rollout.
+
+ Args:
+ request (:class:`~.game_server_configs.DeleteGameServerConfigRequest`):
+ The request object. Request message for
+ GameServerConfigsService.DeleteGameServerConfig.
+ name (:class:`str`):
+ Required. The name of the game server config to delete.
+ Uses the form:
+
+ ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_configs.DeleteGameServerConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.delete_game_server_config,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ empty.Empty,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+
+try:
+ _client_info = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution(
+ "google-cloud-game-servers",
+ ).version,
+ )
+except pkg_resources.DistributionNotFound:
+ _client_info = gapic_v1.client_info.ClientInfo()
+
+
+__all__ = ("GameServerConfigsServiceAsyncClient",)
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/client.py b/google/cloud/gaming_v1/services/game_server_configs_service/client.py
index 92c31ef5..7228a69b 100644
--- a/google/cloud/gaming_v1/services/game_server_configs_service/client.py
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/client.py
@@ -16,6 +16,7 @@
#
from collections import OrderedDict
+import os
import re
from typing import Callable, Dict, Sequence, Tuple, Type, Union
import pkg_resources
@@ -25,16 +26,21 @@
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
+from google.auth.transport import mtls # type: ignore
+from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.api_core import operation
+from google.api_core import operation_async
from google.cloud.gaming_v1.services.game_server_configs_service import pagers
from google.cloud.gaming_v1.types import common
from google.cloud.gaming_v1.types import game_server_configs
+from google.protobuf import empty_pb2 as empty # type: ignore
from google.protobuf import timestamp_pb2 as timestamp # type: ignore
from .transports.base import GameServerConfigsServiceTransport
from .transports.grpc import GameServerConfigsServiceGrpcTransport
+from .transports.grpc_asyncio import GameServerConfigsServiceGrpcAsyncIOTransport
class GameServerConfigsServiceClientMeta(type):
@@ -49,9 +55,10 @@ class GameServerConfigsServiceClientMeta(type):
OrderedDict()
) # type: Dict[str, Type[GameServerConfigsServiceTransport]]
_transport_registry["grpc"] = GameServerConfigsServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = GameServerConfigsServiceGrpcAsyncIOTransport
def get_transport_class(
- cls, label: str = None
+ cls, label: str = None,
) -> Type[GameServerConfigsServiceTransport]:
"""Return an appropriate transport class.
@@ -72,7 +79,7 @@ def get_transport_class(
class GameServerConfigsServiceClient(metaclass=GameServerConfigsServiceClientMeta):
- """The Game Server Config configures the game servers in an
+ """The game server config configures the game servers in an
Agones fleet.
"""
@@ -132,11 +139,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@staticmethod
def game_server_config_path(
- project: str, location: str, deployment: str, config: str
+ project: str, location: str, deployment: str, config: str,
) -> str:
"""Return a fully-qualified game_server_config string."""
return "projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}".format(
- project=project, location=location, deployment=deployment, config=config
+ project=project, location=location, deployment=deployment, config=config,
)
@staticmethod
@@ -166,65 +173,74 @@ def __init__(
transport (Union[str, ~.GameServerConfigsServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (ClientOptions): Custom options for the client.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
- default endpoint provided by the client.
- (2) If ``transport`` argument is None, ``client_options`` can be
- used to create a mutual TLS transport. If ``client_cert_source``
- is provided, mutual TLS transport will be created with the given
- ``api_endpoint`` or the default mTLS endpoint, and the client
- SSL credentials obtained from ``client_cert_source``.
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = ClientOptions.from_dict(client_options)
+ if client_options is None:
+ client_options = ClientOptions.ClientOptions()
+
+ if client_options.api_endpoint is None:
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never")
+ if use_mtls_env == "never":
+ client_options.api_endpoint = self.DEFAULT_ENDPOINT
+ elif use_mtls_env == "always":
+ client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ elif use_mtls_env == "auto":
+ has_client_cert_source = (
+ client_options.client_cert_source is not None
+ or mtls.has_default_client_cert_source()
+ )
+ client_options.api_endpoint = (
+ self.DEFAULT_MTLS_ENDPOINT
+ if has_client_cert_source
+ else self.DEFAULT_ENDPOINT
+ )
+ else:
+ raise MutualTLSChannelError(
+ "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always"
+ )
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, GameServerConfigsServiceTransport):
# transport is a GameServerConfigsServiceTransport instance.
- if credentials:
+ if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
+ if client_options.scopes:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its scopes directly."
+ )
self._transport = transport
- elif client_options is None or (
- client_options.api_endpoint is None
- and client_options.client_cert_source is None
- ):
- # Don't trigger mTLS if we get an empty ClientOptions.
+ else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
- credentials=credentials, host=self.DEFAULT_ENDPOINT
- )
- else:
- # We have a non-empty ClientOptions. If client_cert_source is
- # provided, trigger mTLS with user provided endpoint or the default
- # mTLS endpoint.
- if client_options.client_cert_source:
- api_mtls_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_MTLS_ENDPOINT
- )
- else:
- api_mtls_endpoint = None
-
- api_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_ENDPOINT
- )
-
- self._transport = GameServerConfigsServiceGrpcTransport(
credentials=credentials,
- host=api_endpoint,
- api_mtls_endpoint=api_mtls_endpoint,
+ credentials_file=client_options.credentials_file,
+ host=client_options.api_endpoint,
+ scopes=client_options.scopes,
+ api_mtls_endpoint=client_options.api_endpoint,
client_cert_source=client_options.client_cert_source,
)
@@ -237,8 +253,8 @@ def list_game_server_configs(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListGameServerConfigsPager:
- r"""Lists Game Server Configs in a given project,
- Location, and Game Server Deployment.
+ r"""Lists game server configs in a given project,
+ location, and game server deployment.
Args:
request (:class:`~.game_server_configs.ListGameServerConfigsRequest`):
@@ -299,12 +315,12 @@ def list_game_server_configs(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListGameServerConfigsPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -319,14 +335,14 @@ def get_game_server_config(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> game_server_configs.GameServerConfig:
- r"""Gets details of a single Game Server Config.
+ r"""Gets details of a single game server config.
Args:
request (:class:`~.game_server_configs.GetGameServerConfigRequest`):
The request object. Request message for
GameServerConfigsService.GetGameServerConfig.
name (:class:`str`):
- Required. The name of the Game Server Config to
+ Required. The name of the game server config to
retrieve. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``.
@@ -342,7 +358,7 @@ def get_game_server_config(
Returns:
~.game_server_configs.GameServerConfig:
- A Game Server Config resource.
+ A game server config resource.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
@@ -376,7 +392,7 @@ def get_game_server_config(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -391,10 +407,10 @@ def create_game_server_config(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Creates a new Game Server Config in a given project,
- Location, and Game Server Deployment. Game Server
- Configs are immutable, and are not applied until
- referenced in the Game Server Deployment Rollout
+ r"""Creates a new game server config in a given project,
+ location, and game server deployment. Game server
+ configs are immutable, and are not applied until
+ referenced in the game server deployment rollout
resource.
Args:
@@ -409,7 +425,7 @@ def create_game_server_config(
on the ``request`` instance; if ``request`` is provided, this
should not be set.
game_server_config (:class:`~.game_server_configs.GameServerConfig`):
- Required. The Game Server Config
+ Required. The game server config
resource to be created.
This corresponds to the ``game_server_config`` field
on the ``request`` instance; if ``request`` is provided, this
@@ -427,7 +443,7 @@ def create_game_server_config(
The result type for the operation will be
:class:``~.game_server_configs.GameServerConfig``: A
- Game Server Config resource.
+ game server config resource.
"""
# Create or coerce a protobuf request object.
@@ -457,8 +473,14 @@ def create_game_server_config(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -480,16 +502,16 @@ def delete_game_server_config(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Deletes a single Game Server Config. The deletion
- will fail if the Game Server Config is referenced in a
- Game Server Deployment Rollout.
+ r"""Deletes a single game server config. The deletion
+ will fail if the game server config is referenced in a
+ game server deployment rollout.
Args:
request (:class:`~.game_server_configs.DeleteGameServerConfigRequest`):
The request object. Request message for
GameServerConfigsService.DeleteGameServerConfig.
name (:class:`str`):
- Required. The name of the Game Server Config to delete.
+ Required. The name of the game server config to delete.
Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``.
@@ -508,8 +530,20 @@ def delete_game_server_config(
An object representing a long-running operation.
The result type for the operation will be
- :class:``~.game_server_configs.GameServerConfig``: A
- Game Server Config resource.
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
"""
# Create or coerce a protobuf request object.
@@ -537,14 +571,20 @@ def delete_game_server_config(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
response,
self._transport.operations_client,
- game_server_configs.GameServerConfig,
+ empty.Empty,
metadata_type=common.OperationMetadata,
)
@@ -555,8 +595,8 @@ def delete_game_server_config(
try:
_client_info = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
- "google-cloud-game-servers"
- ).version
+ "google-cloud-game-servers",
+ ).version,
)
except pkg_resources.DistributionNotFound:
_client_info = gapic_v1.client_info.ClientInfo()
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/pagers.py b/google/cloud/gaming_v1/services/game_server_configs_service/pagers.py
index 1e53d52b..538eef8f 100644
--- a/google/cloud/gaming_v1/services/game_server_configs_service/pagers.py
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/pagers.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-from typing import Any, Callable, Iterable
+from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
from google.cloud.gaming_v1.types import game_server_configs
@@ -40,12 +40,11 @@ class ListGameServerConfigsPager:
def __init__(
self,
- method: Callable[
- [game_server_configs.ListGameServerConfigsRequest],
- game_server_configs.ListGameServerConfigsResponse,
- ],
+ method: Callable[..., game_server_configs.ListGameServerConfigsResponse],
request: game_server_configs.ListGameServerConfigsRequest,
response: game_server_configs.ListGameServerConfigsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -56,10 +55,13 @@ def __init__(
The initial request object.
response (:class:`~.game_server_configs.ListGameServerConfigsResponse`):
The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
"""
self._method = method
self._request = game_server_configs.ListGameServerConfigsRequest(request)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@@ -69,7 +71,7 @@ def pages(self) -> Iterable[game_server_configs.ListGameServerConfigsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[game_server_configs.GameServerConfig]:
@@ -78,3 +80,73 @@ def __iter__(self) -> Iterable[game_server_configs.GameServerConfig]:
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class ListGameServerConfigsAsyncPager:
+ """A pager for iterating through ``list_game_server_configs`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.game_server_configs.ListGameServerConfigsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``game_server_configs`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListGameServerConfigs`` requests and continue to iterate
+ through the ``game_server_configs`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.game_server_configs.ListGameServerConfigsResponse`
+ attributes are available on the pager. If multiple requests are made, only
+ the most recent response is retained, and thus used for attribute lookup.
+ """
+
+ def __init__(
+ self,
+ method: Callable[
+ ..., Awaitable[game_server_configs.ListGameServerConfigsResponse]
+ ],
+ request: game_server_configs.ListGameServerConfigsRequest,
+ response: game_server_configs.ListGameServerConfigsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.game_server_configs.ListGameServerConfigsRequest`):
+ The initial request object.
+ response (:class:`~.game_server_configs.ListGameServerConfigsResponse`):
+ The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ self._method = method
+ self._request = game_server_configs.ListGameServerConfigsRequest(request)
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(
+ self,
+ ) -> AsyncIterable[game_server_configs.ListGameServerConfigsResponse]:
+ yield self._response
+ while self._response.next_page_token:
+ self._request.page_token = self._response.next_page_token
+ self._response = await self._method(self._request, metadata=self._metadata)
+ yield self._response
+
+ def __aiter__(self) -> AsyncIterable[game_server_configs.GameServerConfig]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.game_server_configs:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/transports/__init__.py b/google/cloud/gaming_v1/services/game_server_configs_service/transports/__init__.py
index f89612f9..5aa419a6 100644
--- a/google/cloud/gaming_v1/services/game_server_configs_service/transports/__init__.py
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/transports/__init__.py
@@ -20,6 +20,7 @@
from .base import GameServerConfigsServiceTransport
from .grpc import GameServerConfigsServiceGrpcTransport
+from .grpc_asyncio import GameServerConfigsServiceGrpcAsyncIOTransport
# Compile a registry of transports.
@@ -27,6 +28,11 @@
OrderedDict()
) # type: Dict[str, Type[GameServerConfigsServiceTransport]]
_transport_registry["grpc"] = GameServerConfigsServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = GameServerConfigsServiceGrpcAsyncIOTransport
-__all__ = ("GameServerConfigsServiceTransport", "GameServerConfigsServiceGrpcTransport")
+__all__ = (
+ "GameServerConfigsServiceTransport",
+ "GameServerConfigsServiceGrpcTransport",
+ "GameServerConfigsServiceGrpcAsyncIOTransport",
+)
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/transports/base.py b/google/cloud/gaming_v1/services/game_server_configs_service/transports/base.py
index 334bd8ac..158f8d60 100644
--- a/google/cloud/gaming_v1/services/game_server_configs_service/transports/base.py
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/transports/base.py
@@ -19,6 +19,7 @@
import typing
from google import auth
+from google.api_core import exceptions # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.auth import credentials # type: ignore
@@ -26,7 +27,7 @@
from google.longrunning import operations_pb2 as operations # type: ignore
-class GameServerConfigsServiceTransport(metaclass=abc.ABCMeta):
+class GameServerConfigsServiceTransport(abc.ABC):
"""Abstract transport class for GameServerConfigsService."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
@@ -36,6 +37,9 @@ def __init__(
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: typing.Optional[str] = None,
+ scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
+ **kwargs,
) -> None:
"""Instantiate the transport.
@@ -46,6 +50,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scope (Optional[Sequence[str]]): A list of scopes.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
@@ -54,8 +62,17 @@ def __init__(
# If no credentials are provided, then determine the appropriate
# defaults.
- if credentials is None:
- credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+ if credentials and credentials_file:
+ raise exceptions.DuplicateCredentialArgs(
+ "'credentials_file' and 'credentials' are mutually exclusive"
+ )
+
+ if credentials_file is not None:
+ credentials, _ = auth.load_credentials_from_file(
+ credentials_file, scopes=scopes
+ )
+ elif credentials is None:
+ credentials, _ = auth.default(scopes=scopes)
# Save the credentials.
self._credentials = credentials
@@ -63,41 +80,49 @@ def __init__(
@property
def operations_client(self) -> operations_v1.OperationsClient:
"""Return the client designed to process long-running operations."""
- raise NotImplementedError
+ raise NotImplementedError()
@property
def list_game_server_configs(
- self
+ self,
) -> typing.Callable[
[game_server_configs.ListGameServerConfigsRequest],
- game_server_configs.ListGameServerConfigsResponse,
+ typing.Union[
+ game_server_configs.ListGameServerConfigsResponse,
+ typing.Awaitable[game_server_configs.ListGameServerConfigsResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def get_game_server_config(
- self
+ self,
) -> typing.Callable[
[game_server_configs.GetGameServerConfigRequest],
- game_server_configs.GameServerConfig,
+ typing.Union[
+ game_server_configs.GameServerConfig,
+ typing.Awaitable[game_server_configs.GameServerConfig],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def create_game_server_config(
- self
+ self,
) -> typing.Callable[
- [game_server_configs.CreateGameServerConfigRequest], operations.Operation
+ [game_server_configs.CreateGameServerConfigRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def delete_game_server_config(
- self
+ self,
) -> typing.Callable[
- [game_server_configs.DeleteGameServerConfigRequest], operations.Operation
+ [game_server_configs.DeleteGameServerConfigRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
__all__ = ("GameServerConfigsServiceTransport",)
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/transports/grpc.py b/google/cloud/gaming_v1/services/game_server_configs_service/transports/grpc.py
index 7caf2d34..473cce24 100644
--- a/google/cloud/gaming_v1/services/game_server_configs_service/transports/grpc.py
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/transports/grpc.py
@@ -15,10 +15,11 @@
# limitations under the License.
#
-from typing import Callable, Dict, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
+from google import auth # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
@@ -34,7 +35,7 @@
class GameServerConfigsServiceGrpcTransport(GameServerConfigsServiceTransport):
"""gRPC backend transport for GameServerConfigsService.
- The Game Server Config configures the game servers in an
+ The game server config configures the game servers in an
Agones fleet.
This class defines the same methods as the primary client, so the
@@ -45,11 +46,15 @@ class GameServerConfigsServiceGrpcTransport(GameServerConfigsServiceTransport):
top of HTTP/2); the ``grpcio`` package must be installed.
"""
+ _stubs: Dict[str, Callable]
+
def __init__(
self,
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
@@ -64,6 +69,11 @@ def __init__(
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
+ ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
@@ -76,8 +86,10 @@ def __init__(
is None.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
if channel:
# Sanity check: Ensure that channel and credentials are not both
@@ -93,6 +105,9 @@ def __init__(
else api_mtls_endpoint + ":443"
)
+ if credentials is None:
+ credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
@@ -104,15 +119,22 @@ def __init__(
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
- self._grpc_channel = grpc_helpers.create_channel(
+ self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
+ credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
- scopes=self.AUTH_SCOPES,
+ scopes=scopes or self.AUTH_SCOPES,
)
# Run the base constructor.
- super().__init__(host=host, credentials=credentials)
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
self._stubs = {} # type: Dict[str, Callable]
@classmethod
@@ -120,6 +142,8 @@ def create_channel(
cls,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Optional[Sequence[str]] = None,
**kwargs
) -> grpc.Channel:
"""Create and return a gRPC channel object.
@@ -130,13 +154,28 @@ def create_channel(
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
+
+ Raises:
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
+ scopes = scopes or cls.AUTH_SCOPES
return grpc_helpers.create_channel(
- host, credentials=credentials, scopes=cls.AUTH_SCOPES, **kwargs
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
)
@property
@@ -150,7 +189,7 @@ def grpc_channel(self) -> grpc.Channel:
# have one.
if not hasattr(self, "_grpc_channel"):
self._grpc_channel = self.create_channel(
- self._host, credentials=self._credentials
+ self._host, credentials=self._credentials,
)
# Return the channel from cache.
@@ -174,15 +213,15 @@ def operations_client(self) -> operations_v1.OperationsClient:
@property
def list_game_server_configs(
- self
+ self,
) -> Callable[
[game_server_configs.ListGameServerConfigsRequest],
game_server_configs.ListGameServerConfigsResponse,
]:
r"""Return a callable for the list game server configs method over gRPC.
- Lists Game Server Configs in a given project,
- Location, and Game Server Deployment.
+ Lists game server configs in a given project,
+ location, and game server deployment.
Returns:
Callable[[~.ListGameServerConfigsRequest],
@@ -204,14 +243,14 @@ def list_game_server_configs(
@property
def get_game_server_config(
- self
+ self,
) -> Callable[
[game_server_configs.GetGameServerConfigRequest],
game_server_configs.GameServerConfig,
]:
r"""Return a callable for the get game server config method over gRPC.
- Gets details of a single Game Server Config.
+ Gets details of a single game server config.
Returns:
Callable[[~.GetGameServerConfigRequest],
@@ -233,16 +272,16 @@ def get_game_server_config(
@property
def create_game_server_config(
- self
+ self,
) -> Callable[
[game_server_configs.CreateGameServerConfigRequest], operations.Operation
]:
r"""Return a callable for the create game server config method over gRPC.
- Creates a new Game Server Config in a given project,
- Location, and Game Server Deployment. Game Server
- Configs are immutable, and are not applied until
- referenced in the Game Server Deployment Rollout
+ Creates a new game server config in a given project,
+ location, and game server deployment. Game server
+ configs are immutable, and are not applied until
+ referenced in the game server deployment rollout
resource.
Returns:
@@ -265,15 +304,15 @@ def create_game_server_config(
@property
def delete_game_server_config(
- self
+ self,
) -> Callable[
[game_server_configs.DeleteGameServerConfigRequest], operations.Operation
]:
r"""Return a callable for the delete game server config method over gRPC.
- Deletes a single Game Server Config. The deletion
- will fail if the Game Server Config is referenced in a
- Game Server Deployment Rollout.
+ Deletes a single game server config. The deletion
+ will fail if the game server config is referenced in a
+ game server deployment rollout.
Returns:
Callable[[~.DeleteGameServerConfigRequest],
diff --git a/google/cloud/gaming_v1/services/game_server_configs_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1/services/game_server_configs_service/transports/grpc_asyncio.py
new file mode 100644
index 00000000..c97ac06e
--- /dev/null
+++ b/google/cloud/gaming_v1/services/game_server_configs_service/transports/grpc_asyncio.py
@@ -0,0 +1,333 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+
+from google.api_core import grpc_helpers_async # type: ignore
+from google.api_core import operations_v1 # type: ignore
+from google.auth import credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+
+import grpc # type: ignore
+from grpc.experimental import aio # type: ignore
+
+from google.cloud.gaming_v1.types import game_server_configs
+from google.longrunning import operations_pb2 as operations # type: ignore
+
+from .base import GameServerConfigsServiceTransport
+from .grpc import GameServerConfigsServiceGrpcTransport
+
+
+class GameServerConfigsServiceGrpcAsyncIOTransport(GameServerConfigsServiceTransport):
+ """gRPC AsyncIO backend transport for GameServerConfigsService.
+
+ The game server config configures the game servers in an
+ Agones fleet.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends protocol buffers over the wire using gRPC (which is built on
+ top of HTTP/2); the ``grpcio`` package must be installed.
+ """
+
+ _grpc_channel: aio.Channel
+ _stubs: Dict[str, Callable] = {}
+
+ @classmethod
+ def create_channel(
+ cls,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ **kwargs
+ ) -> aio.Channel:
+ """Create and return a gRPC AsyncIO channel object.
+ Args:
+ address (Optional[str]): The host for the channel to use.
+ credentials (Optional[~.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify this application to the service. If
+ none are specified, the client will attempt to ascertain
+ the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
+ channel creation.
+ Returns:
+ aio.Channel: A gRPC AsyncIO channel object.
+ """
+ scopes = scopes or cls.AUTH_SCOPES
+ return grpc_helpers_async.create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
+ )
+
+ def __init__(
+ self,
+ *,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ channel: aio.Channel = None,
+ api_mtls_endpoint: str = None,
+ client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]): The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ channel (Optional[aio.Channel]): A ``Channel`` instance through
+ which to make calls.
+ api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
+ provided, it overrides the ``host`` argument and tries to create
+ a mutual TLS channel with client SSL credentials from
+ ``client_cert_source`` or applicatin default SSL credentials.
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
+ callback to provide client SSL certificate bytes and private key
+ bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
+ is None.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
+ """
+ if channel:
+ # Sanity check: Ensure that channel and credentials are not both
+ # provided.
+ credentials = False
+
+ # If a channel was explicitly provided, set it.
+ self._grpc_channel = channel
+ elif api_mtls_endpoint:
+ host = (
+ api_mtls_endpoint
+ if ":" in api_mtls_endpoint
+ else api_mtls_endpoint + ":443"
+ )
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ ssl_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ ssl_credentials = SslCredentials().ssl_credentials
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ # Run the base constructor.
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ self._stubs = {}
+
+ @property
+ def grpc_channel(self) -> aio.Channel:
+ """Create the channel designed to connect to this service.
+
+ This property caches on the instance; repeated calls return
+ the same channel.
+ """
+ # Sanity check: Only create a new channel if we do not already
+ # have one.
+ if not hasattr(self, "_grpc_channel"):
+ self._grpc_channel = self.create_channel(
+ self._host, credentials=self._credentials,
+ )
+
+ # Return the channel from cache.
+ return self._grpc_channel
+
+ @property
+ def operations_client(self) -> operations_v1.OperationsAsyncClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Sanity check: Only create a new client if we do not already have one.
+ if "operations_client" not in self.__dict__:
+ self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient(
+ self.grpc_channel
+ )
+
+ # Return the client from cache.
+ return self.__dict__["operations_client"]
+
+ @property
+ def list_game_server_configs(
+ self,
+ ) -> Callable[
+ [game_server_configs.ListGameServerConfigsRequest],
+ Awaitable[game_server_configs.ListGameServerConfigsResponse],
+ ]:
+ r"""Return a callable for the list game server configs method over gRPC.
+
+ Lists game server configs in a given project,
+ location, and game server deployment.
+
+ Returns:
+ Callable[[~.ListGameServerConfigsRequest],
+ Awaitable[~.ListGameServerConfigsResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "list_game_server_configs" not in self._stubs:
+ self._stubs["list_game_server_configs"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerConfigsService/ListGameServerConfigs",
+ request_serializer=game_server_configs.ListGameServerConfigsRequest.serialize,
+ response_deserializer=game_server_configs.ListGameServerConfigsResponse.deserialize,
+ )
+ return self._stubs["list_game_server_configs"]
+
+ @property
+ def get_game_server_config(
+ self,
+ ) -> Callable[
+ [game_server_configs.GetGameServerConfigRequest],
+ Awaitable[game_server_configs.GameServerConfig],
+ ]:
+ r"""Return a callable for the get game server config method over gRPC.
+
+ Gets details of a single game server config.
+
+ Returns:
+ Callable[[~.GetGameServerConfigRequest],
+ Awaitable[~.GameServerConfig]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_game_server_config" not in self._stubs:
+ self._stubs["get_game_server_config"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerConfigsService/GetGameServerConfig",
+ request_serializer=game_server_configs.GetGameServerConfigRequest.serialize,
+ response_deserializer=game_server_configs.GameServerConfig.deserialize,
+ )
+ return self._stubs["get_game_server_config"]
+
+ @property
+ def create_game_server_config(
+ self,
+ ) -> Callable[
+ [game_server_configs.CreateGameServerConfigRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the create game server config method over gRPC.
+
+ Creates a new game server config in a given project,
+ location, and game server deployment. Game server
+ configs are immutable, and are not applied until
+ referenced in the game server deployment rollout
+ resource.
+
+ Returns:
+ Callable[[~.CreateGameServerConfigRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "create_game_server_config" not in self._stubs:
+ self._stubs["create_game_server_config"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerConfigsService/CreateGameServerConfig",
+ request_serializer=game_server_configs.CreateGameServerConfigRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["create_game_server_config"]
+
+ @property
+ def delete_game_server_config(
+ self,
+ ) -> Callable[
+ [game_server_configs.DeleteGameServerConfigRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the delete game server config method over gRPC.
+
+ Deletes a single game server config. The deletion
+ will fail if the game server config is referenced in a
+ game server deployment rollout.
+
+ Returns:
+ Callable[[~.DeleteGameServerConfigRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_game_server_config" not in self._stubs:
+ self._stubs["delete_game_server_config"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerConfigsService/DeleteGameServerConfig",
+ request_serializer=game_server_configs.DeleteGameServerConfigRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["delete_game_server_config"]
+
+
+__all__ = ("GameServerConfigsServiceGrpcAsyncIOTransport",)
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/__init__.py b/google/cloud/gaming_v1/services/game_server_deployments_service/__init__.py
index 23cc6c38..b24578bc 100644
--- a/google/cloud/gaming_v1/services/game_server_deployments_service/__init__.py
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/__init__.py
@@ -16,5 +16,9 @@
#
from .client import GameServerDeploymentsServiceClient
+from .async_client import GameServerDeploymentsServiceAsyncClient
-__all__ = ("GameServerDeploymentsServiceClient",)
+__all__ = (
+ "GameServerDeploymentsServiceClient",
+ "GameServerDeploymentsServiceAsyncClient",
+)
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/async_client.py b/google/cloud/gaming_v1/services/game_server_deployments_service/async_client.py
new file mode 100644
index 00000000..71cd7a05
--- /dev/null
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/async_client.py
@@ -0,0 +1,855 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections import OrderedDict
+import functools
+import re
+from typing import Dict, Sequence, Tuple, Type, Union
+import pkg_resources
+
+import google.api_core.client_options as ClientOptions # type: ignore
+from google.api_core import exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.auth import credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
+
+from google.api_core import operation
+from google.api_core import operation_async
+from google.cloud.gaming_v1.services.game_server_deployments_service import pagers
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import game_server_deployments
+from google.protobuf import empty_pb2 as empty # type: ignore
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+from .transports.base import GameServerDeploymentsServiceTransport
+from .transports.grpc_asyncio import GameServerDeploymentsServiceGrpcAsyncIOTransport
+from .client import GameServerDeploymentsServiceClient
+
+
+class GameServerDeploymentsServiceAsyncClient:
+ """The game server deployment is used to control the deployment
+ of Agones fleets.
+ """
+
+ _client: GameServerDeploymentsServiceClient
+
+ DEFAULT_ENDPOINT = GameServerDeploymentsServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = GameServerDeploymentsServiceClient.DEFAULT_MTLS_ENDPOINT
+
+ game_server_deployment_path = staticmethod(
+ GameServerDeploymentsServiceClient.game_server_deployment_path
+ )
+
+ game_server_deployment_rollout_path = staticmethod(
+ GameServerDeploymentsServiceClient.game_server_deployment_rollout_path
+ )
+
+ from_service_account_file = (
+ GameServerDeploymentsServiceClient.from_service_account_file
+ )
+ from_service_account_json = from_service_account_file
+
+ get_transport_class = functools.partial(
+ type(GameServerDeploymentsServiceClient).get_transport_class,
+ type(GameServerDeploymentsServiceClient),
+ )
+
+ def __init__(
+ self,
+ *,
+ credentials: credentials.Credentials = None,
+ transport: Union[str, GameServerDeploymentsServiceTransport] = "grpc_asyncio",
+ client_options: ClientOptions = None,
+ ) -> None:
+ """Instantiate the game server deployments service client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, ~.GameServerDeploymentsServiceTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+
+ self._client = GameServerDeploymentsServiceClient(
+ credentials=credentials, transport=transport, client_options=client_options,
+ )
+
+ async def list_game_server_deployments(
+ self,
+ request: game_server_deployments.ListGameServerDeploymentsRequest = None,
+ *,
+ parent: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListGameServerDeploymentsAsyncPager:
+ r"""Lists game server deployments in a given project and
+ location.
+
+ Args:
+ request (:class:`~.game_server_deployments.ListGameServerDeploymentsRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.ListGameServerDeployments.
+ parent (:class:`str`):
+ Required. The parent resource name. Uses the form:
+ ``projects/{project}/locations/{location}``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.pagers.ListGameServerDeploymentsAsyncPager:
+ Response message for
+ GameServerDeploymentsService.ListGameServerDeployments.
+ Iterating over this object will yield
+ results and resolve additional pages
+ automatically.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_deployments.ListGameServerDeploymentsRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_game_server_deployments,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.ListGameServerDeploymentsAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_game_server_deployment(
+ self,
+ request: game_server_deployments.GetGameServerDeploymentRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_deployments.GameServerDeployment:
+ r"""Gets details of a single game server deployment.
+
+ Args:
+ request (:class:`~.game_server_deployments.GetGameServerDeploymentRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.GetGameServerDeployment.
+ name (:class:`str`):
+ Required. The name of the game server delpoyment to
+ retrieve. Uses the form:
+
+ ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_deployments.GameServerDeployment:
+ A game server deployment resource.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_deployments.GetGameServerDeploymentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_game_server_deployment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def create_game_server_deployment(
+ self,
+ request: game_server_deployments.CreateGameServerDeploymentRequest = None,
+ *,
+ parent: str = None,
+ game_server_deployment: game_server_deployments.GameServerDeployment = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Creates a new game server deployment in a given
+ project and location.
+
+ Args:
+ request (:class:`~.game_server_deployments.CreateGameServerDeploymentRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.CreateGameServerDeployment.
+ parent (:class:`str`):
+ Required. The parent resource name. Uses the form:
+ ``projects/{project}/locations/{location}``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ game_server_deployment (:class:`~.game_server_deployments.GameServerDeployment`):
+ Required. The game server delpoyment
+ resource to be created.
+ This corresponds to the ``game_server_deployment`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.game_server_deployments.GameServerDeployment``:
+ A game server deployment resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent, game_server_deployment]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_deployments.CreateGameServerDeploymentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if game_server_deployment is not None:
+ request.game_server_deployment = game_server_deployment
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.create_game_server_deployment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ game_server_deployments.GameServerDeployment,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def delete_game_server_deployment(
+ self,
+ request: game_server_deployments.DeleteGameServerDeploymentRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Deletes a single game server deployment.
+
+ Args:
+ request (:class:`~.game_server_deployments.DeleteGameServerDeploymentRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.DeleteGameServerDeployment.
+ name (:class:`str`):
+ Required. The name of the game server delpoyment to
+ delete. Uses the form:
+
+ ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_deployments.DeleteGameServerDeploymentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.delete_game_server_deployment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ empty.Empty,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def update_game_server_deployment(
+ self,
+ request: game_server_deployments.UpdateGameServerDeploymentRequest = None,
+ *,
+ game_server_deployment: game_server_deployments.GameServerDeployment = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Patches a game server deployment.
+
+ Args:
+ request (:class:`~.game_server_deployments.UpdateGameServerDeploymentRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.UpdateGameServerDeployment.
+ Only allows updates for labels.
+ game_server_deployment (:class:`~.game_server_deployments.GameServerDeployment`):
+ Required. The game server delpoyment to be updated. Only
+ fields specified in update_mask are updated.
+ This corresponds to the ``game_server_deployment`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Required. Mask of fields to update. At least one path
+ must be supplied in this field. For the ``FieldMask``
+ definition, see
+
+ https: //developers.google.com/protocol-buffers //
+ /docs/reference/google.protobuf#fieldmask
+ This corresponds to the ``update_mask`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.game_server_deployments.GameServerDeployment``:
+ A game server deployment resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([game_server_deployment, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_deployments.UpdateGameServerDeploymentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if game_server_deployment is not None:
+ request.game_server_deployment = game_server_deployment
+ if update_mask is not None:
+ request.update_mask = update_mask
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.update_game_server_deployment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("game_server_deployment.name", request.game_server_deployment.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ game_server_deployments.GameServerDeployment,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_game_server_deployment_rollout(
+ self,
+ request: game_server_deployments.GetGameServerDeploymentRolloutRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_deployments.GameServerDeploymentRollout:
+ r"""Gets details a single game server deployment rollout.
+
+ Args:
+ request (:class:`~.game_server_deployments.GetGameServerDeploymentRolloutRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.GetGameServerDeploymentRollout.
+ name (:class:`str`):
+ Required. The name of the game server delpoyment to
+ retrieve. Uses the form:
+
+ ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_deployments.GameServerDeploymentRollout:
+ The game server deployment rollout
+ which represents the desired rollout
+ state.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_deployments.GetGameServerDeploymentRolloutRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_game_server_deployment_rollout,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def update_game_server_deployment_rollout(
+ self,
+ request: game_server_deployments.UpdateGameServerDeploymentRolloutRequest = None,
+ *,
+ rollout: game_server_deployments.GameServerDeploymentRollout = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Patches a single game server deployment rollout. The method will
+ not return an error if the update does not affect any existing
+ realms. For example - if the default_game_server_config is
+ changed but all existing realms use the override, that is valid.
+ Similarly, if a non existing realm is explicitly called out in
+ game_server_config_overrides field, that will also not result in
+ an error.
+
+ Args:
+ request (:class:`~.game_server_deployments.UpdateGameServerDeploymentRolloutRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.UpdateGameServerRolloutDeployment.
+ rollout (:class:`~.game_server_deployments.GameServerDeploymentRollout`):
+ Required. The game server delpoyment rollout to be
+ updated. Only fields specified in update_mask are
+ updated.
+ This corresponds to the ``rollout`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Required. Mask of fields to update. At least one path
+ must be supplied in this field. For the ``FieldMask``
+ definition, see
+
+ https: //developers.google.com/protocol-buffers //
+ /docs/reference/google.protobuf#fieldmask
+ This corresponds to the ``update_mask`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.game_server_deployments.GameServerDeployment``:
+ A game server deployment resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([rollout, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = game_server_deployments.UpdateGameServerDeploymentRolloutRequest(
+ request
+ )
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if rollout is not None:
+ request.rollout = rollout
+ if update_mask is not None:
+ request.update_mask = update_mask
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.update_game_server_deployment_rollout,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("rollout.name", request.rollout.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ game_server_deployments.GameServerDeployment,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def preview_game_server_deployment_rollout(
+ self,
+ request: game_server_deployments.PreviewGameServerDeploymentRolloutRequest = None,
+ *,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_deployments.PreviewGameServerDeploymentRolloutResponse:
+ r"""Previews the game server deployment rollout. This API
+ does not mutate the rollout resource.
+
+ Args:
+ request (:class:`~.game_server_deployments.PreviewGameServerDeploymentRolloutRequest`):
+ The request object. Request message for
+ PreviewGameServerDeploymentRollout.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_deployments.PreviewGameServerDeploymentRolloutResponse:
+ Response message for
+ PreviewGameServerDeploymentRollout. This
+ has details about the Agones fleet and
+ autoscaler to be actuated.
+
+ """
+ # Create or coerce a protobuf request object.
+
+ request = game_server_deployments.PreviewGameServerDeploymentRolloutRequest(
+ request
+ )
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.preview_game_server_deployment_rollout,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("rollout.name", request.rollout.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def fetch_deployment_state(
+ self,
+ request: game_server_deployments.FetchDeploymentStateRequest = None,
+ *,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> game_server_deployments.FetchDeploymentStateResponse:
+ r"""Retrieves information about the current state of the
+ game server deployment. Gathers all the Agones fleets
+ and Agones autoscalers, including fleets running an
+ older version of the game server deployment.
+
+ Args:
+ request (:class:`~.game_server_deployments.FetchDeploymentStateRequest`):
+ The request object. Request message for
+ GameServerDeploymentsService.FetchDeploymentState.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.game_server_deployments.FetchDeploymentStateResponse:
+ Response message for
+ GameServerDeploymentsService.FetchDeploymentState.
+
+ """
+ # Create or coerce a protobuf request object.
+
+ request = game_server_deployments.FetchDeploymentStateRequest(request)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.fetch_deployment_state,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+
+try:
+ _client_info = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution(
+ "google-cloud-game-servers",
+ ).version,
+ )
+except pkg_resources.DistributionNotFound:
+ _client_info = gapic_v1.client_info.ClientInfo()
+
+
+__all__ = ("GameServerDeploymentsServiceAsyncClient",)
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/client.py b/google/cloud/gaming_v1/services/game_server_deployments_service/client.py
index 3419bb0f..b4eae774 100644
--- a/google/cloud/gaming_v1/services/game_server_deployments_service/client.py
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/client.py
@@ -16,6 +16,7 @@
#
from collections import OrderedDict
+import os
import re
from typing import Callable, Dict, Sequence, Tuple, Type, Union
import pkg_resources
@@ -25,17 +26,22 @@
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
+from google.auth.transport import mtls # type: ignore
+from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.api_core import operation
+from google.api_core import operation_async
from google.cloud.gaming_v1.services.game_server_deployments_service import pagers
from google.cloud.gaming_v1.types import common
from google.cloud.gaming_v1.types import game_server_deployments
+from google.protobuf import empty_pb2 as empty # type: ignore
from google.protobuf import field_mask_pb2 as field_mask # type: ignore
from google.protobuf import timestamp_pb2 as timestamp # type: ignore
from .transports.base import GameServerDeploymentsServiceTransport
from .transports.grpc import GameServerDeploymentsServiceGrpcTransport
+from .transports.grpc_asyncio import GameServerDeploymentsServiceGrpcAsyncIOTransport
class GameServerDeploymentsServiceClientMeta(type):
@@ -50,9 +56,12 @@ class GameServerDeploymentsServiceClientMeta(type):
OrderedDict()
) # type: Dict[str, Type[GameServerDeploymentsServiceTransport]]
_transport_registry["grpc"] = GameServerDeploymentsServiceGrpcTransport
+ _transport_registry[
+ "grpc_asyncio"
+ ] = GameServerDeploymentsServiceGrpcAsyncIOTransport
def get_transport_class(
- cls, label: str = None
+ cls, label: str = None,
) -> Type[GameServerDeploymentsServiceTransport]:
"""Return an appropriate transport class.
@@ -75,7 +84,7 @@ def get_transport_class(
class GameServerDeploymentsServiceClient(
metaclass=GameServerDeploymentsServiceClientMeta
):
- """The Game Server Deployment is used to control the deployment
+ """The game server deployment is used to control the deployment
of Agones fleets.
"""
@@ -134,37 +143,37 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
from_service_account_json = from_service_account_file
@staticmethod
- def game_server_deployment_rollout_path(
- project: str, location: str, deployment: str
+ def game_server_deployment_path(
+ project: str, location: str, deployment: str,
) -> str:
- """Return a fully-qualified game_server_deployment_rollout string."""
- return "projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout".format(
- project=project, location=location, deployment=deployment
+ """Return a fully-qualified game_server_deployment string."""
+ return "projects/{project}/locations/{location}/gameServerDeployments/{deployment}".format(
+ project=project, location=location, deployment=deployment,
)
@staticmethod
- def parse_game_server_deployment_rollout_path(path: str) -> Dict[str, str]:
- """Parse a game_server_deployment_rollout path into its component segments."""
+ def parse_game_server_deployment_path(path: str) -> Dict[str, str]:
+ """Parse a game_server_deployment path into its component segments."""
m = re.match(
- r"^projects/(?P
.+?)/locations/(?P.+?)/gameServerDeployments/(?P.+?)/rollout$",
+ r"^projects/(?P.+?)/locations/(?P.+?)/gameServerDeployments/(?P.+?)$",
path,
)
return m.groupdict() if m else {}
@staticmethod
- def game_server_deployment_path(
- project: str, location: str, deployment: str
+ def game_server_deployment_rollout_path(
+ project: str, location: str, deployment: str,
) -> str:
- """Return a fully-qualified game_server_deployment string."""
- return "projects/{project}/locations/{location}/gameServerDeployments/{deployment}".format(
- project=project, location=location, deployment=deployment
+ """Return a fully-qualified game_server_deployment_rollout string."""
+ return "projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout".format(
+ project=project, location=location, deployment=deployment,
)
@staticmethod
- def parse_game_server_deployment_path(path: str) -> Dict[str, str]:
- """Parse a game_server_deployment path into its component segments."""
+ def parse_game_server_deployment_rollout_path(path: str) -> Dict[str, str]:
+ """Parse a game_server_deployment_rollout path into its component segments."""
m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/gameServerDeployments/(?P.+?)$",
+ r"^projects/(?P.+?)/locations/(?P.+?)/gameServerDeployments/(?P.+?)/rollout$",
path,
)
return m.groupdict() if m else {}
@@ -187,65 +196,74 @@ def __init__(
transport (Union[str, ~.GameServerDeploymentsServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (ClientOptions): Custom options for the client.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
- default endpoint provided by the client.
- (2) If ``transport`` argument is None, ``client_options`` can be
- used to create a mutual TLS transport. If ``client_cert_source``
- is provided, mutual TLS transport will be created with the given
- ``api_endpoint`` or the default mTLS endpoint, and the client
- SSL credentials obtained from ``client_cert_source``.
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = ClientOptions.from_dict(client_options)
+ if client_options is None:
+ client_options = ClientOptions.ClientOptions()
+
+ if client_options.api_endpoint is None:
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never")
+ if use_mtls_env == "never":
+ client_options.api_endpoint = self.DEFAULT_ENDPOINT
+ elif use_mtls_env == "always":
+ client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ elif use_mtls_env == "auto":
+ has_client_cert_source = (
+ client_options.client_cert_source is not None
+ or mtls.has_default_client_cert_source()
+ )
+ client_options.api_endpoint = (
+ self.DEFAULT_MTLS_ENDPOINT
+ if has_client_cert_source
+ else self.DEFAULT_ENDPOINT
+ )
+ else:
+ raise MutualTLSChannelError(
+ "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always"
+ )
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, GameServerDeploymentsServiceTransport):
# transport is a GameServerDeploymentsServiceTransport instance.
- if credentials:
+ if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
+ if client_options.scopes:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its scopes directly."
+ )
self._transport = transport
- elif client_options is None or (
- client_options.api_endpoint is None
- and client_options.client_cert_source is None
- ):
- # Don't trigger mTLS if we get an empty ClientOptions.
+ else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
- credentials=credentials, host=self.DEFAULT_ENDPOINT
- )
- else:
- # We have a non-empty ClientOptions. If client_cert_source is
- # provided, trigger mTLS with user provided endpoint or the default
- # mTLS endpoint.
- if client_options.client_cert_source:
- api_mtls_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_MTLS_ENDPOINT
- )
- else:
- api_mtls_endpoint = None
-
- api_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_ENDPOINT
- )
-
- self._transport = GameServerDeploymentsServiceGrpcTransport(
credentials=credentials,
- host=api_endpoint,
- api_mtls_endpoint=api_mtls_endpoint,
+ credentials_file=client_options.credentials_file,
+ host=client_options.api_endpoint,
+ scopes=client_options.scopes,
+ api_mtls_endpoint=client_options.api_endpoint,
client_cert_source=client_options.client_cert_source,
)
@@ -258,8 +276,8 @@ def list_game_server_deployments(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListGameServerDeploymentsPager:
- r"""Lists Game Server Deployments in a given project and
- Location.
+ r"""Lists game server deployments in a given project and
+ location.
Args:
request (:class:`~.game_server_deployments.ListGameServerDeploymentsRequest`):
@@ -319,12 +337,12 @@ def list_game_server_deployments(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListGameServerDeploymentsPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -339,14 +357,14 @@ def get_game_server_deployment(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> game_server_deployments.GameServerDeployment:
- r"""Gets details of a single Game Server Deployment.
+ r"""Gets details of a single game server deployment.
Args:
request (:class:`~.game_server_deployments.GetGameServerDeploymentRequest`):
The request object. Request message for
GameServerDeploymentsService.GetGameServerDeployment.
name (:class:`str`):
- Required. The name of the Game Server Deployment to
+ Required. The name of the game server delpoyment to
retrieve. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
@@ -362,7 +380,7 @@ def get_game_server_deployment(
Returns:
~.game_server_deployments.GameServerDeployment:
- A Game Server Deployment resource.
+ A game server deployment resource.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
@@ -396,7 +414,7 @@ def get_game_server_deployment(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -411,8 +429,8 @@ def create_game_server_deployment(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Creates a new Game Server Deployment in a given
- project and Location.
+ r"""Creates a new game server deployment in a given
+ project and location.
Args:
request (:class:`~.game_server_deployments.CreateGameServerDeploymentRequest`):
@@ -425,7 +443,7 @@ def create_game_server_deployment(
on the ``request`` instance; if ``request`` is provided, this
should not be set.
game_server_deployment (:class:`~.game_server_deployments.GameServerDeployment`):
- Required. The Game Server Deployment
+ Required. The game server delpoyment
resource to be created.
This corresponds to the ``game_server_deployment`` field
on the ``request`` instance; if ``request`` is provided, this
@@ -443,7 +461,7 @@ def create_game_server_deployment(
The result type for the operation will be
:class:``~.game_server_deployments.GameServerDeployment``:
- A Game Server Deployment resource.
+ A game server deployment resource.
"""
# Create or coerce a protobuf request object.
@@ -473,8 +491,14 @@ def create_game_server_deployment(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -496,14 +520,14 @@ def delete_game_server_deployment(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Deletes a single Game Server Deployment.
+ r"""Deletes a single game server deployment.
Args:
request (:class:`~.game_server_deployments.DeleteGameServerDeploymentRequest`):
The request object. Request message for
GameServerDeploymentsService.DeleteGameServerDeployment.
name (:class:`str`):
- Required. The name of the Game Server Deployment to
+ Required. The name of the game server delpoyment to
delete. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
@@ -522,8 +546,20 @@ def delete_game_server_deployment(
An object representing a long-running operation.
The result type for the operation will be
- :class:``~.game_server_deployments.GameServerDeployment``:
- A Game Server Deployment resource.
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
"""
# Create or coerce a protobuf request object.
@@ -551,14 +587,20 @@ def delete_game_server_deployment(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
response,
self._transport.operations_client,
- game_server_deployments.GameServerDeployment,
+ empty.Empty,
metadata_type=common.OperationMetadata,
)
@@ -575,7 +617,7 @@ def update_game_server_deployment(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Patches a Game Server Deployment.
+ r"""Patches a game server deployment.
Args:
request (:class:`~.game_server_deployments.UpdateGameServerDeploymentRequest`):
@@ -583,7 +625,7 @@ def update_game_server_deployment(
GameServerDeploymentsService.UpdateGameServerDeployment.
Only allows updates for labels.
game_server_deployment (:class:`~.game_server_deployments.GameServerDeployment`):
- Required. The Game Server Deployment to be updated. Only
+ Required. The game server delpoyment to be updated. Only
fields specified in update_mask are updated.
This corresponds to the ``game_server_deployment`` field
on the ``request`` instance; if ``request`` is provided, this
@@ -611,7 +653,7 @@ def update_game_server_deployment(
The result type for the operation will be
:class:``~.game_server_deployments.GameServerDeployment``:
- A Game Server Deployment resource.
+ A game server deployment resource.
"""
# Create or coerce a protobuf request object.
@@ -641,8 +683,16 @@ def update_game_server_deployment(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("game_server_deployment.name", request.game_server_deployment.name),)
+ ),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -664,14 +714,14 @@ def get_game_server_deployment_rollout(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> game_server_deployments.GameServerDeploymentRollout:
- r"""Gets details a single Game Server Deployment Rollout.
+ r"""Gets details a single game server deployment rollout.
Args:
request (:class:`~.game_server_deployments.GetGameServerDeploymentRolloutRequest`):
The request object. Request message for
GameServerDeploymentsService.GetGameServerDeploymentRollout.
name (:class:`str`):
- Required. The name of the Game Server Deployment to
+ Required. The name of the game server delpoyment to
retrieve. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout``.
@@ -687,7 +737,7 @@ def get_game_server_deployment_rollout(
Returns:
~.game_server_deployments.GameServerDeploymentRollout:
- The Game Server Deployment Rollout
+ The game server deployment rollout
which represents the desired rollout
state.
@@ -724,7 +774,7 @@ def get_game_server_deployment_rollout(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -739,7 +789,7 @@ def update_game_server_deployment_rollout(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Patches a single Game Server Deployment Rollout. The method will
+ r"""Patches a single game server deployment rollout. The method will
not return an error if the update does not affect any existing
realms. For example - if the default_game_server_config is
changed but all existing realms use the override, that is valid.
@@ -752,7 +802,7 @@ def update_game_server_deployment_rollout(
The request object. Request message for
GameServerDeploymentsService.UpdateGameServerRolloutDeployment.
rollout (:class:`~.game_server_deployments.GameServerDeploymentRollout`):
- Required. The Game Server Deployment Rollout to be
+ Required. The game server delpoyment rollout to be
updated. Only fields specified in update_mask are
updated.
This corresponds to the ``rollout`` field
@@ -781,7 +831,7 @@ def update_game_server_deployment_rollout(
The result type for the operation will be
:class:``~.game_server_deployments.GameServerDeployment``:
- A Game Server Deployment resource.
+ A game server deployment resource.
"""
# Create or coerce a protobuf request object.
@@ -813,8 +863,16 @@ def update_game_server_deployment_rollout(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("rollout.name", request.rollout.name),)
+ ),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -835,8 +893,8 @@ def preview_game_server_deployment_rollout(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> game_server_deployments.PreviewGameServerDeploymentRolloutResponse:
- r"""Previews the Game Server Deployment Rollout. This API
- does not mutate the Rollout resource.
+ r"""Previews the game server deployment rollout. This API
+ does not mutate the rollout resource.
Args:
request (:class:`~.game_server_deployments.PreviewGameServerDeploymentRolloutRequest`):
@@ -871,8 +929,16 @@ def preview_game_server_deployment_rollout(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("rollout.name", request.rollout.name),)
+ ),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -886,9 +952,9 @@ def fetch_deployment_state(
metadata: Sequence[Tuple[str, str]] = (),
) -> game_server_deployments.FetchDeploymentStateResponse:
r"""Retrieves information about the current state of the
- Game Server Ddeployment. Gathers all the Agones fleets
+ game server deployment. Gathers all the Agones fleets
and Agones autoscalers, including fleets running an
- older version of the Game Server Deployment.
+ older version of the game server deployment.
Args:
request (:class:`~.game_server_deployments.FetchDeploymentStateRequest`):
@@ -919,8 +985,14 @@ def fetch_deployment_state(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -929,8 +1001,8 @@ def fetch_deployment_state(
try:
_client_info = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
- "google-cloud-game-servers"
- ).version
+ "google-cloud-game-servers",
+ ).version,
)
except pkg_resources.DistributionNotFound:
_client_info = gapic_v1.client_info.ClientInfo()
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/pagers.py b/google/cloud/gaming_v1/services/game_server_deployments_service/pagers.py
index 91e7934a..5fed613e 100644
--- a/google/cloud/gaming_v1/services/game_server_deployments_service/pagers.py
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/pagers.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-from typing import Any, Callable, Iterable
+from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
from google.cloud.gaming_v1.types import game_server_deployments
@@ -41,11 +41,12 @@ class ListGameServerDeploymentsPager:
def __init__(
self,
method: Callable[
- [game_server_deployments.ListGameServerDeploymentsRequest],
- game_server_deployments.ListGameServerDeploymentsResponse,
+ ..., game_server_deployments.ListGameServerDeploymentsResponse
],
request: game_server_deployments.ListGameServerDeploymentsRequest,
response: game_server_deployments.ListGameServerDeploymentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -56,24 +57,27 @@ def __init__(
The initial request object.
response (:class:`~.game_server_deployments.ListGameServerDeploymentsResponse`):
The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
"""
self._method = method
self._request = game_server_deployments.ListGameServerDeploymentsRequest(
request
)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(
- self
+ self,
) -> Iterable[game_server_deployments.ListGameServerDeploymentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[game_server_deployments.GameServerDeployment]:
@@ -82,3 +86,75 @@ def __iter__(self) -> Iterable[game_server_deployments.GameServerDeployment]:
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class ListGameServerDeploymentsAsyncPager:
+ """A pager for iterating through ``list_game_server_deployments`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.game_server_deployments.ListGameServerDeploymentsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``game_server_deployments`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListGameServerDeployments`` requests and continue to iterate
+ through the ``game_server_deployments`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.game_server_deployments.ListGameServerDeploymentsResponse`
+ attributes are available on the pager. If multiple requests are made, only
+ the most recent response is retained, and thus used for attribute lookup.
+ """
+
+ def __init__(
+ self,
+ method: Callable[
+ ..., Awaitable[game_server_deployments.ListGameServerDeploymentsResponse]
+ ],
+ request: game_server_deployments.ListGameServerDeploymentsRequest,
+ response: game_server_deployments.ListGameServerDeploymentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.game_server_deployments.ListGameServerDeploymentsRequest`):
+ The initial request object.
+ response (:class:`~.game_server_deployments.ListGameServerDeploymentsResponse`):
+ The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ self._method = method
+ self._request = game_server_deployments.ListGameServerDeploymentsRequest(
+ request
+ )
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(
+ self,
+ ) -> AsyncIterable[game_server_deployments.ListGameServerDeploymentsResponse]:
+ yield self._response
+ while self._response.next_page_token:
+ self._request.page_token = self._response.next_page_token
+ self._response = await self._method(self._request, metadata=self._metadata)
+ yield self._response
+
+ def __aiter__(self) -> AsyncIterable[game_server_deployments.GameServerDeployment]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.game_server_deployments:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/transports/__init__.py b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/__init__.py
index b954a6aa..17e99cc0 100644
--- a/google/cloud/gaming_v1/services/game_server_deployments_service/transports/__init__.py
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/__init__.py
@@ -20,6 +20,7 @@
from .base import GameServerDeploymentsServiceTransport
from .grpc import GameServerDeploymentsServiceGrpcTransport
+from .grpc_asyncio import GameServerDeploymentsServiceGrpcAsyncIOTransport
# Compile a registry of transports.
@@ -27,9 +28,11 @@
OrderedDict()
) # type: Dict[str, Type[GameServerDeploymentsServiceTransport]]
_transport_registry["grpc"] = GameServerDeploymentsServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = GameServerDeploymentsServiceGrpcAsyncIOTransport
__all__ = (
"GameServerDeploymentsServiceTransport",
"GameServerDeploymentsServiceGrpcTransport",
+ "GameServerDeploymentsServiceGrpcAsyncIOTransport",
)
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/transports/base.py b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/base.py
index eea3137d..6004e163 100644
--- a/google/cloud/gaming_v1/services/game_server_deployments_service/transports/base.py
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/base.py
@@ -19,6 +19,7 @@
import typing
from google import auth
+from google.api_core import exceptions # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.auth import credentials # type: ignore
@@ -26,7 +27,7 @@
from google.longrunning import operations_pb2 as operations # type: ignore
-class GameServerDeploymentsServiceTransport(metaclass=abc.ABCMeta):
+class GameServerDeploymentsServiceTransport(abc.ABC):
"""Abstract transport class for GameServerDeploymentsService."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
@@ -36,6 +37,9 @@ def __init__(
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: typing.Optional[str] = None,
+ scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
+ **kwargs,
) -> None:
"""Instantiate the transport.
@@ -46,6 +50,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scope (Optional[Sequence[str]]): A list of scopes.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
@@ -54,8 +62,17 @@ def __init__(
# If no credentials are provided, then determine the appropriate
# defaults.
- if credentials is None:
- credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+ if credentials and credentials_file:
+ raise exceptions.DuplicateCredentialArgs(
+ "'credentials_file' and 'credentials' are mutually exclusive"
+ )
+
+ if credentials_file is not None:
+ credentials, _ = auth.load_credentials_from_file(
+ credentials_file, scopes=scopes
+ )
+ elif credentials is None:
+ credentials, _ = auth.default(scopes=scopes)
# Save the credentials.
self._credentials = credentials
@@ -63,88 +80,105 @@ def __init__(
@property
def operations_client(self) -> operations_v1.OperationsClient:
"""Return the client designed to process long-running operations."""
- raise NotImplementedError
+ raise NotImplementedError()
@property
def list_game_server_deployments(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.ListGameServerDeploymentsRequest],
- game_server_deployments.ListGameServerDeploymentsResponse,
+ typing.Union[
+ game_server_deployments.ListGameServerDeploymentsResponse,
+ typing.Awaitable[game_server_deployments.ListGameServerDeploymentsResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def get_game_server_deployment(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.GetGameServerDeploymentRequest],
- game_server_deployments.GameServerDeployment,
+ typing.Union[
+ game_server_deployments.GameServerDeployment,
+ typing.Awaitable[game_server_deployments.GameServerDeployment],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def create_game_server_deployment(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.CreateGameServerDeploymentRequest],
- operations.Operation,
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def delete_game_server_deployment(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.DeleteGameServerDeploymentRequest],
- operations.Operation,
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def update_game_server_deployment(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.UpdateGameServerDeploymentRequest],
- operations.Operation,
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def get_game_server_deployment_rollout(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.GetGameServerDeploymentRolloutRequest],
- game_server_deployments.GameServerDeploymentRollout,
+ typing.Union[
+ game_server_deployments.GameServerDeploymentRollout,
+ typing.Awaitable[game_server_deployments.GameServerDeploymentRollout],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def update_game_server_deployment_rollout(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.UpdateGameServerDeploymentRolloutRequest],
- operations.Operation,
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def preview_game_server_deployment_rollout(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.PreviewGameServerDeploymentRolloutRequest],
- game_server_deployments.PreviewGameServerDeploymentRolloutResponse,
+ typing.Union[
+ game_server_deployments.PreviewGameServerDeploymentRolloutResponse,
+ typing.Awaitable[
+ game_server_deployments.PreviewGameServerDeploymentRolloutResponse
+ ],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def fetch_deployment_state(
- self
+ self,
) -> typing.Callable[
[game_server_deployments.FetchDeploymentStateRequest],
- game_server_deployments.FetchDeploymentStateResponse,
+ typing.Union[
+ game_server_deployments.FetchDeploymentStateResponse,
+ typing.Awaitable[game_server_deployments.FetchDeploymentStateResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
__all__ = ("GameServerDeploymentsServiceTransport",)
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc.py b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc.py
index 2ea472d8..ce9f53f6 100644
--- a/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc.py
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc.py
@@ -15,10 +15,11 @@
# limitations under the License.
#
-from typing import Callable, Dict, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
+from google import auth # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
@@ -34,7 +35,7 @@
class GameServerDeploymentsServiceGrpcTransport(GameServerDeploymentsServiceTransport):
"""gRPC backend transport for GameServerDeploymentsService.
- The Game Server Deployment is used to control the deployment
+ The game server deployment is used to control the deployment
of Agones fleets.
This class defines the same methods as the primary client, so the
@@ -45,11 +46,15 @@ class GameServerDeploymentsServiceGrpcTransport(GameServerDeploymentsServiceTran
top of HTTP/2); the ``grpcio`` package must be installed.
"""
+ _stubs: Dict[str, Callable]
+
def __init__(
self,
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
@@ -64,6 +69,11 @@ def __init__(
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
+ ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
@@ -76,8 +86,10 @@ def __init__(
is None.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
if channel:
# Sanity check: Ensure that channel and credentials are not both
@@ -93,6 +105,9 @@ def __init__(
else api_mtls_endpoint + ":443"
)
+ if credentials is None:
+ credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
@@ -104,15 +119,22 @@ def __init__(
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
- self._grpc_channel = grpc_helpers.create_channel(
+ self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
+ credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
- scopes=self.AUTH_SCOPES,
+ scopes=scopes or self.AUTH_SCOPES,
)
# Run the base constructor.
- super().__init__(host=host, credentials=credentials)
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
self._stubs = {} # type: Dict[str, Callable]
@classmethod
@@ -120,6 +142,8 @@ def create_channel(
cls,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Optional[Sequence[str]] = None,
**kwargs
) -> grpc.Channel:
"""Create and return a gRPC channel object.
@@ -130,13 +154,28 @@ def create_channel(
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
+
+ Raises:
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
+ scopes = scopes or cls.AUTH_SCOPES
return grpc_helpers.create_channel(
- host, credentials=credentials, scopes=cls.AUTH_SCOPES, **kwargs
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
)
@property
@@ -150,7 +189,7 @@ def grpc_channel(self) -> grpc.Channel:
# have one.
if not hasattr(self, "_grpc_channel"):
self._grpc_channel = self.create_channel(
- self._host, credentials=self._credentials
+ self._host, credentials=self._credentials,
)
# Return the channel from cache.
@@ -174,15 +213,15 @@ def operations_client(self) -> operations_v1.OperationsClient:
@property
def list_game_server_deployments(
- self
+ self,
) -> Callable[
[game_server_deployments.ListGameServerDeploymentsRequest],
game_server_deployments.ListGameServerDeploymentsResponse,
]:
r"""Return a callable for the list game server deployments method over gRPC.
- Lists Game Server Deployments in a given project and
- Location.
+ Lists game server deployments in a given project and
+ location.
Returns:
Callable[[~.ListGameServerDeploymentsRequest],
@@ -204,14 +243,14 @@ def list_game_server_deployments(
@property
def get_game_server_deployment(
- self
+ self,
) -> Callable[
[game_server_deployments.GetGameServerDeploymentRequest],
game_server_deployments.GameServerDeployment,
]:
r"""Return a callable for the get game server deployment method over gRPC.
- Gets details of a single Game Server Deployment.
+ Gets details of a single game server deployment.
Returns:
Callable[[~.GetGameServerDeploymentRequest],
@@ -233,15 +272,15 @@ def get_game_server_deployment(
@property
def create_game_server_deployment(
- self
+ self,
) -> Callable[
[game_server_deployments.CreateGameServerDeploymentRequest],
operations.Operation,
]:
r"""Return a callable for the create game server deployment method over gRPC.
- Creates a new Game Server Deployment in a given
- project and Location.
+ Creates a new game server deployment in a given
+ project and location.
Returns:
Callable[[~.CreateGameServerDeploymentRequest],
@@ -265,14 +304,14 @@ def create_game_server_deployment(
@property
def delete_game_server_deployment(
- self
+ self,
) -> Callable[
[game_server_deployments.DeleteGameServerDeploymentRequest],
operations.Operation,
]:
r"""Return a callable for the delete game server deployment method over gRPC.
- Deletes a single Game Server Deployment.
+ Deletes a single game server deployment.
Returns:
Callable[[~.DeleteGameServerDeploymentRequest],
@@ -296,14 +335,14 @@ def delete_game_server_deployment(
@property
def update_game_server_deployment(
- self
+ self,
) -> Callable[
[game_server_deployments.UpdateGameServerDeploymentRequest],
operations.Operation,
]:
r"""Return a callable for the update game server deployment method over gRPC.
- Patches a Game Server Deployment.
+ Patches a game server deployment.
Returns:
Callable[[~.UpdateGameServerDeploymentRequest],
@@ -327,7 +366,7 @@ def update_game_server_deployment(
@property
def get_game_server_deployment_rollout(
- self
+ self,
) -> Callable[
[game_server_deployments.GetGameServerDeploymentRolloutRequest],
game_server_deployments.GameServerDeploymentRollout,
@@ -335,7 +374,7 @@ def get_game_server_deployment_rollout(
r"""Return a callable for the get game server deployment
rollout method over gRPC.
- Gets details a single Game Server Deployment Rollout.
+ Gets details a single game server deployment rollout.
Returns:
Callable[[~.GetGameServerDeploymentRolloutRequest],
@@ -359,7 +398,7 @@ def get_game_server_deployment_rollout(
@property
def update_game_server_deployment_rollout(
- self
+ self,
) -> Callable[
[game_server_deployments.UpdateGameServerDeploymentRolloutRequest],
operations.Operation,
@@ -367,7 +406,7 @@ def update_game_server_deployment_rollout(
r"""Return a callable for the update game server deployment
rollout method over gRPC.
- Patches a single Game Server Deployment Rollout. The method will
+ Patches a single game server deployment rollout. The method will
not return an error if the update does not affect any existing
realms. For example - if the default_game_server_config is
changed but all existing realms use the override, that is valid.
@@ -397,7 +436,7 @@ def update_game_server_deployment_rollout(
@property
def preview_game_server_deployment_rollout(
- self
+ self,
) -> Callable[
[game_server_deployments.PreviewGameServerDeploymentRolloutRequest],
game_server_deployments.PreviewGameServerDeploymentRolloutResponse,
@@ -405,8 +444,8 @@ def preview_game_server_deployment_rollout(
r"""Return a callable for the preview game server deployment
rollout method over gRPC.
- Previews the Game Server Deployment Rollout. This API
- does not mutate the Rollout resource.
+ Previews the game server deployment rollout. This API
+ does not mutate the rollout resource.
Returns:
Callable[[~.PreviewGameServerDeploymentRolloutRequest],
@@ -430,7 +469,7 @@ def preview_game_server_deployment_rollout(
@property
def fetch_deployment_state(
- self
+ self,
) -> Callable[
[game_server_deployments.FetchDeploymentStateRequest],
game_server_deployments.FetchDeploymentStateResponse,
@@ -438,9 +477,9 @@ def fetch_deployment_state(
r"""Return a callable for the fetch deployment state method over gRPC.
Retrieves information about the current state of the
- Game Server Ddeployment. Gathers all the Agones fleets
+ game server deployment. Gathers all the Agones fleets
and Agones autoscalers, including fleets running an
- older version of the Game Server Deployment.
+ older version of the game server deployment.
Returns:
Callable[[~.FetchDeploymentStateRequest],
diff --git a/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc_asyncio.py
new file mode 100644
index 00000000..5623d47f
--- /dev/null
+++ b/google/cloud/gaming_v1/services/game_server_deployments_service/transports/grpc_asyncio.py
@@ -0,0 +1,500 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+
+from google.api_core import grpc_helpers_async # type: ignore
+from google.api_core import operations_v1 # type: ignore
+from google.auth import credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+
+import grpc # type: ignore
+from grpc.experimental import aio # type: ignore
+
+from google.cloud.gaming_v1.types import game_server_deployments
+from google.longrunning import operations_pb2 as operations # type: ignore
+
+from .base import GameServerDeploymentsServiceTransport
+from .grpc import GameServerDeploymentsServiceGrpcTransport
+
+
+class GameServerDeploymentsServiceGrpcAsyncIOTransport(
+ GameServerDeploymentsServiceTransport
+):
+ """gRPC AsyncIO backend transport for GameServerDeploymentsService.
+
+ The game server deployment is used to control the deployment
+ of Agones fleets.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends protocol buffers over the wire using gRPC (which is built on
+ top of HTTP/2); the ``grpcio`` package must be installed.
+ """
+
+ _grpc_channel: aio.Channel
+ _stubs: Dict[str, Callable] = {}
+
+ @classmethod
+ def create_channel(
+ cls,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ **kwargs
+ ) -> aio.Channel:
+ """Create and return a gRPC AsyncIO channel object.
+ Args:
+ address (Optional[str]): The host for the channel to use.
+ credentials (Optional[~.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify this application to the service. If
+ none are specified, the client will attempt to ascertain
+ the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
+ channel creation.
+ Returns:
+ aio.Channel: A gRPC AsyncIO channel object.
+ """
+ scopes = scopes or cls.AUTH_SCOPES
+ return grpc_helpers_async.create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
+ )
+
+ def __init__(
+ self,
+ *,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ channel: aio.Channel = None,
+ api_mtls_endpoint: str = None,
+ client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]): The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ channel (Optional[aio.Channel]): A ``Channel`` instance through
+ which to make calls.
+ api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
+ provided, it overrides the ``host`` argument and tries to create
+ a mutual TLS channel with client SSL credentials from
+ ``client_cert_source`` or applicatin default SSL credentials.
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
+ callback to provide client SSL certificate bytes and private key
+ bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
+ is None.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
+ """
+ if channel:
+ # Sanity check: Ensure that channel and credentials are not both
+ # provided.
+ credentials = False
+
+ # If a channel was explicitly provided, set it.
+ self._grpc_channel = channel
+ elif api_mtls_endpoint:
+ host = (
+ api_mtls_endpoint
+ if ":" in api_mtls_endpoint
+ else api_mtls_endpoint + ":443"
+ )
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ ssl_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ ssl_credentials = SslCredentials().ssl_credentials
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ # Run the base constructor.
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ self._stubs = {}
+
+ @property
+ def grpc_channel(self) -> aio.Channel:
+ """Create the channel designed to connect to this service.
+
+ This property caches on the instance; repeated calls return
+ the same channel.
+ """
+ # Sanity check: Only create a new channel if we do not already
+ # have one.
+ if not hasattr(self, "_grpc_channel"):
+ self._grpc_channel = self.create_channel(
+ self._host, credentials=self._credentials,
+ )
+
+ # Return the channel from cache.
+ return self._grpc_channel
+
+ @property
+ def operations_client(self) -> operations_v1.OperationsAsyncClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Sanity check: Only create a new client if we do not already have one.
+ if "operations_client" not in self.__dict__:
+ self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient(
+ self.grpc_channel
+ )
+
+ # Return the client from cache.
+ return self.__dict__["operations_client"]
+
+ @property
+ def list_game_server_deployments(
+ self,
+ ) -> Callable[
+ [game_server_deployments.ListGameServerDeploymentsRequest],
+ Awaitable[game_server_deployments.ListGameServerDeploymentsResponse],
+ ]:
+ r"""Return a callable for the list game server deployments method over gRPC.
+
+ Lists game server deployments in a given project and
+ location.
+
+ Returns:
+ Callable[[~.ListGameServerDeploymentsRequest],
+ Awaitable[~.ListGameServerDeploymentsResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "list_game_server_deployments" not in self._stubs:
+ self._stubs["list_game_server_deployments"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/ListGameServerDeployments",
+ request_serializer=game_server_deployments.ListGameServerDeploymentsRequest.serialize,
+ response_deserializer=game_server_deployments.ListGameServerDeploymentsResponse.deserialize,
+ )
+ return self._stubs["list_game_server_deployments"]
+
+ @property
+ def get_game_server_deployment(
+ self,
+ ) -> Callable[
+ [game_server_deployments.GetGameServerDeploymentRequest],
+ Awaitable[game_server_deployments.GameServerDeployment],
+ ]:
+ r"""Return a callable for the get game server deployment method over gRPC.
+
+ Gets details of a single game server deployment.
+
+ Returns:
+ Callable[[~.GetGameServerDeploymentRequest],
+ Awaitable[~.GameServerDeployment]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_game_server_deployment" not in self._stubs:
+ self._stubs["get_game_server_deployment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/GetGameServerDeployment",
+ request_serializer=game_server_deployments.GetGameServerDeploymentRequest.serialize,
+ response_deserializer=game_server_deployments.GameServerDeployment.deserialize,
+ )
+ return self._stubs["get_game_server_deployment"]
+
+ @property
+ def create_game_server_deployment(
+ self,
+ ) -> Callable[
+ [game_server_deployments.CreateGameServerDeploymentRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the create game server deployment method over gRPC.
+
+ Creates a new game server deployment in a given
+ project and location.
+
+ Returns:
+ Callable[[~.CreateGameServerDeploymentRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "create_game_server_deployment" not in self._stubs:
+ self._stubs[
+ "create_game_server_deployment"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/CreateGameServerDeployment",
+ request_serializer=game_server_deployments.CreateGameServerDeploymentRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["create_game_server_deployment"]
+
+ @property
+ def delete_game_server_deployment(
+ self,
+ ) -> Callable[
+ [game_server_deployments.DeleteGameServerDeploymentRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the delete game server deployment method over gRPC.
+
+ Deletes a single game server deployment.
+
+ Returns:
+ Callable[[~.DeleteGameServerDeploymentRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_game_server_deployment" not in self._stubs:
+ self._stubs[
+ "delete_game_server_deployment"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/DeleteGameServerDeployment",
+ request_serializer=game_server_deployments.DeleteGameServerDeploymentRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["delete_game_server_deployment"]
+
+ @property
+ def update_game_server_deployment(
+ self,
+ ) -> Callable[
+ [game_server_deployments.UpdateGameServerDeploymentRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the update game server deployment method over gRPC.
+
+ Patches a game server deployment.
+
+ Returns:
+ Callable[[~.UpdateGameServerDeploymentRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "update_game_server_deployment" not in self._stubs:
+ self._stubs[
+ "update_game_server_deployment"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/UpdateGameServerDeployment",
+ request_serializer=game_server_deployments.UpdateGameServerDeploymentRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["update_game_server_deployment"]
+
+ @property
+ def get_game_server_deployment_rollout(
+ self,
+ ) -> Callable[
+ [game_server_deployments.GetGameServerDeploymentRolloutRequest],
+ Awaitable[game_server_deployments.GameServerDeploymentRollout],
+ ]:
+ r"""Return a callable for the get game server deployment
+ rollout method over gRPC.
+
+ Gets details a single game server deployment rollout.
+
+ Returns:
+ Callable[[~.GetGameServerDeploymentRolloutRequest],
+ Awaitable[~.GameServerDeploymentRollout]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_game_server_deployment_rollout" not in self._stubs:
+ self._stubs[
+ "get_game_server_deployment_rollout"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/GetGameServerDeploymentRollout",
+ request_serializer=game_server_deployments.GetGameServerDeploymentRolloutRequest.serialize,
+ response_deserializer=game_server_deployments.GameServerDeploymentRollout.deserialize,
+ )
+ return self._stubs["get_game_server_deployment_rollout"]
+
+ @property
+ def update_game_server_deployment_rollout(
+ self,
+ ) -> Callable[
+ [game_server_deployments.UpdateGameServerDeploymentRolloutRequest],
+ Awaitable[operations.Operation],
+ ]:
+ r"""Return a callable for the update game server deployment
+ rollout method over gRPC.
+
+ Patches a single game server deployment rollout. The method will
+ not return an error if the update does not affect any existing
+ realms. For example - if the default_game_server_config is
+ changed but all existing realms use the override, that is valid.
+ Similarly, if a non existing realm is explicitly called out in
+ game_server_config_overrides field, that will also not result in
+ an error.
+
+ Returns:
+ Callable[[~.UpdateGameServerDeploymentRolloutRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "update_game_server_deployment_rollout" not in self._stubs:
+ self._stubs[
+ "update_game_server_deployment_rollout"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/UpdateGameServerDeploymentRollout",
+ request_serializer=game_server_deployments.UpdateGameServerDeploymentRolloutRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["update_game_server_deployment_rollout"]
+
+ @property
+ def preview_game_server_deployment_rollout(
+ self,
+ ) -> Callable[
+ [game_server_deployments.PreviewGameServerDeploymentRolloutRequest],
+ Awaitable[game_server_deployments.PreviewGameServerDeploymentRolloutResponse],
+ ]:
+ r"""Return a callable for the preview game server deployment
+ rollout method over gRPC.
+
+ Previews the game server deployment rollout. This API
+ does not mutate the rollout resource.
+
+ Returns:
+ Callable[[~.PreviewGameServerDeploymentRolloutRequest],
+ Awaitable[~.PreviewGameServerDeploymentRolloutResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "preview_game_server_deployment_rollout" not in self._stubs:
+ self._stubs[
+ "preview_game_server_deployment_rollout"
+ ] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/PreviewGameServerDeploymentRollout",
+ request_serializer=game_server_deployments.PreviewGameServerDeploymentRolloutRequest.serialize,
+ response_deserializer=game_server_deployments.PreviewGameServerDeploymentRolloutResponse.deserialize,
+ )
+ return self._stubs["preview_game_server_deployment_rollout"]
+
+ @property
+ def fetch_deployment_state(
+ self,
+ ) -> Callable[
+ [game_server_deployments.FetchDeploymentStateRequest],
+ Awaitable[game_server_deployments.FetchDeploymentStateResponse],
+ ]:
+ r"""Return a callable for the fetch deployment state method over gRPC.
+
+ Retrieves information about the current state of the
+ game server deployment. Gathers all the Agones fleets
+ and Agones autoscalers, including fleets running an
+ older version of the game server deployment.
+
+ Returns:
+ Callable[[~.FetchDeploymentStateRequest],
+ Awaitable[~.FetchDeploymentStateResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "fetch_deployment_state" not in self._stubs:
+ self._stubs["fetch_deployment_state"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.GameServerDeploymentsService/FetchDeploymentState",
+ request_serializer=game_server_deployments.FetchDeploymentStateRequest.serialize,
+ response_deserializer=game_server_deployments.FetchDeploymentStateResponse.deserialize,
+ )
+ return self._stubs["fetch_deployment_state"]
+
+
+__all__ = ("GameServerDeploymentsServiceGrpcAsyncIOTransport",)
diff --git a/google/cloud/gaming_v1/services/realms_service/__init__.py b/google/cloud/gaming_v1/services/realms_service/__init__.py
index f6bb8520..bef41506 100644
--- a/google/cloud/gaming_v1/services/realms_service/__init__.py
+++ b/google/cloud/gaming_v1/services/realms_service/__init__.py
@@ -16,5 +16,9 @@
#
from .client import RealmsServiceClient
+from .async_client import RealmsServiceAsyncClient
-__all__ = ("RealmsServiceClient",)
+__all__ = (
+ "RealmsServiceClient",
+ "RealmsServiceAsyncClient",
+)
diff --git a/google/cloud/gaming_v1/services/realms_service/async_client.py b/google/cloud/gaming_v1/services/realms_service/async_client.py
new file mode 100644
index 00000000..07eb9dfd
--- /dev/null
+++ b/google/cloud/gaming_v1/services/realms_service/async_client.py
@@ -0,0 +1,608 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections import OrderedDict
+import functools
+import re
+from typing import Dict, Sequence, Tuple, Type, Union
+import pkg_resources
+
+import google.api_core.client_options as ClientOptions # type: ignore
+from google.api_core import exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.auth import credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
+
+from google.api_core import operation
+from google.api_core import operation_async
+from google.cloud.gaming_v1.services.realms_service import pagers
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import realms
+from google.protobuf import empty_pb2 as empty # type: ignore
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+from .transports.base import RealmsServiceTransport
+from .transports.grpc_asyncio import RealmsServiceGrpcAsyncIOTransport
+from .client import RealmsServiceClient
+
+
+class RealmsServiceAsyncClient:
+ """A realm is a grouping of game server clusters that are
+ considered interchangeable.
+ """
+
+ _client: RealmsServiceClient
+
+ DEFAULT_ENDPOINT = RealmsServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = RealmsServiceClient.DEFAULT_MTLS_ENDPOINT
+
+ realm_path = staticmethod(RealmsServiceClient.realm_path)
+
+ from_service_account_file = RealmsServiceClient.from_service_account_file
+ from_service_account_json = from_service_account_file
+
+ get_transport_class = functools.partial(
+ type(RealmsServiceClient).get_transport_class, type(RealmsServiceClient)
+ )
+
+ def __init__(
+ self,
+ *,
+ credentials: credentials.Credentials = None,
+ transport: Union[str, RealmsServiceTransport] = "grpc_asyncio",
+ client_options: ClientOptions = None,
+ ) -> None:
+ """Instantiate the realms service client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, ~.RealmsServiceTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+
+ self._client = RealmsServiceClient(
+ credentials=credentials, transport=transport, client_options=client_options,
+ )
+
+ async def list_realms(
+ self,
+ request: realms.ListRealmsRequest = None,
+ *,
+ parent: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListRealmsAsyncPager:
+ r"""Lists realms in a given project and location.
+
+ Args:
+ request (:class:`~.realms.ListRealmsRequest`):
+ The request object. Request message for
+ RealmsService.ListRealms.
+ parent (:class:`str`):
+ Required. The parent resource name. Uses the form:
+ ``projects/{project}/locations/{location}``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.pagers.ListRealmsAsyncPager:
+ Response message for
+ RealmsService.ListRealms.
+ Iterating over this object will yield
+ results and resolve additional pages
+ automatically.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = realms.ListRealmsRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.list_realms,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.ListRealmsAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_realm(
+ self,
+ request: realms.GetRealmRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> realms.Realm:
+ r"""Gets details of a single realm.
+
+ Args:
+ request (:class:`~.realms.GetRealmRequest`):
+ The request object. Request message for
+ RealmsService.GetRealm.
+ name (:class:`str`):
+ Required. The name of the realm to retrieve. Uses the
+ form:
+ ``projects/{project}/locations/{location}/realms/{realm}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.realms.Realm:
+ A realm resource.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = realms.GetRealmRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_realm,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def create_realm(
+ self,
+ request: realms.CreateRealmRequest = None,
+ *,
+ parent: str = None,
+ realm: realms.Realm = None,
+ realm_id: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Creates a new realm in a given project and location.
+
+ Args:
+ request (:class:`~.realms.CreateRealmRequest`):
+ The request object. Request message for
+ RealmsService.CreateRealm.
+ parent (:class:`str`):
+ Required. The parent resource name. Uses the form:
+ ``projects/{project}/locations/{location}``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ realm (:class:`~.realms.Realm`):
+ Required. The realm resource to be
+ created.
+ This corresponds to the ``realm`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ realm_id (:class:`str`):
+ Required. The ID of the realm
+ resource to be created.
+ This corresponds to the ``realm_id`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.realms.Realm``: A realm resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent, realm, realm_id]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = realms.CreateRealmRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if realm is not None:
+ request.realm = realm
+ if realm_id is not None:
+ request.realm_id = realm_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.create_realm,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ realms.Realm,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def delete_realm(
+ self,
+ request: realms.DeleteRealmRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Deletes a single realm.
+
+ Args:
+ request (:class:`~.realms.DeleteRealmRequest`):
+ The request object. Request message for
+ RealmsService.DeleteRealm.
+ name (:class:`str`):
+ Required. The name of the realm to delete. Uses the
+ form:
+ ``projects/{project}/locations/{location}/realms/{realm}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = realms.DeleteRealmRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.delete_realm,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ empty.Empty,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def update_realm(
+ self,
+ request: realms.UpdateRealmRequest = None,
+ *,
+ realm: realms.Realm = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> operation_async.AsyncOperation:
+ r"""Patches a single realm.
+
+ Args:
+ request (:class:`~.realms.UpdateRealmRequest`):
+ The request object. Request message for
+ RealmsService.UpdateRealm.
+ realm (:class:`~.realms.Realm`):
+ Required. The realm to be updated. Only fields specified
+ in update_mask are updated.
+ This corresponds to the ``realm`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Required. The update mask applies to the resource. For
+ the ``FieldMask`` definition, see
+
+ https: //developers.google.com/protocol-buffers //
+ /docs/reference/google.protobuf#fieldmask
+ This corresponds to the ``update_mask`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.operation_async.AsyncOperation:
+ An object representing a long-running operation.
+
+ The result type for the operation will be
+ :class:``~.realms.Realm``: A realm resource.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([realm, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = realms.UpdateRealmRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if realm is not None:
+ request.realm = realm
+ if update_mask is not None:
+ request.update_mask = update_mask
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.update_realm,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("realm.name", request.realm.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ realms.Realm,
+ metadata_type=common.OperationMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def preview_realm_update(
+ self,
+ request: realms.PreviewRealmUpdateRequest = None,
+ *,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> realms.PreviewRealmUpdateResponse:
+ r"""Previews patches to a single realm.
+
+ Args:
+ request (:class:`~.realms.PreviewRealmUpdateRequest`):
+ The request object. Request message for
+ RealmsService.PreviewRealmUpdate.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.realms.PreviewRealmUpdateResponse:
+ Response message for
+ RealmsService.PreviewRealmUpdate.
+
+ """
+ # Create or coerce a protobuf request object.
+
+ request = realms.PreviewRealmUpdateRequest(request)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.preview_realm_update,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("realm.name", request.realm.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+
+try:
+ _client_info = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution(
+ "google-cloud-game-servers",
+ ).version,
+ )
+except pkg_resources.DistributionNotFound:
+ _client_info = gapic_v1.client_info.ClientInfo()
+
+
+__all__ = ("RealmsServiceAsyncClient",)
diff --git a/google/cloud/gaming_v1/services/realms_service/client.py b/google/cloud/gaming_v1/services/realms_service/client.py
index 17bc445d..38f71642 100644
--- a/google/cloud/gaming_v1/services/realms_service/client.py
+++ b/google/cloud/gaming_v1/services/realms_service/client.py
@@ -16,6 +16,7 @@
#
from collections import OrderedDict
+import os
import re
from typing import Callable, Dict, Sequence, Tuple, Type, Union
import pkg_resources
@@ -25,17 +26,22 @@
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
+from google.auth.transport import mtls # type: ignore
+from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.api_core import operation
+from google.api_core import operation_async
from google.cloud.gaming_v1.services.realms_service import pagers
from google.cloud.gaming_v1.types import common
from google.cloud.gaming_v1.types import realms
+from google.protobuf import empty_pb2 as empty # type: ignore
from google.protobuf import field_mask_pb2 as field_mask # type: ignore
from google.protobuf import timestamp_pb2 as timestamp # type: ignore
from .transports.base import RealmsServiceTransport
from .transports.grpc import RealmsServiceGrpcTransport
+from .transports.grpc_asyncio import RealmsServiceGrpcAsyncIOTransport
class RealmsServiceClientMeta(type):
@@ -48,8 +54,9 @@ class RealmsServiceClientMeta(type):
_transport_registry = OrderedDict() # type: Dict[str, Type[RealmsServiceTransport]]
_transport_registry["grpc"] = RealmsServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = RealmsServiceGrpcAsyncIOTransport
- def get_transport_class(cls, label: str = None) -> Type[RealmsServiceTransport]:
+ def get_transport_class(cls, label: str = None,) -> Type[RealmsServiceTransport]:
"""Return an appropriate transport class.
Args:
@@ -69,7 +76,7 @@ def get_transport_class(cls, label: str = None) -> Type[RealmsServiceTransport]:
class RealmsServiceClient(metaclass=RealmsServiceClientMeta):
- """A Realm is a grouping of Game Server Clusters that are
+ """A realm is a grouping of game server clusters that are
considered interchangeable.
"""
@@ -128,10 +135,10 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
from_service_account_json = from_service_account_file
@staticmethod
- def realm_path(project: str, location: str, realm: str) -> str:
+ def realm_path(project: str, location: str, realm: str,) -> str:
"""Return a fully-qualified realm string."""
return "projects/{project}/locations/{location}/realms/{realm}".format(
- project=project, location=location, realm=realm
+ project=project, location=location, realm=realm,
)
@staticmethod
@@ -161,65 +168,74 @@ def __init__(
transport (Union[str, ~.RealmsServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (ClientOptions): Custom options for the client.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
- default endpoint provided by the client.
- (2) If ``transport`` argument is None, ``client_options`` can be
- used to create a mutual TLS transport. If ``client_cert_source``
- is provided, mutual TLS transport will be created with the given
- ``api_endpoint`` or the default mTLS endpoint, and the client
- SSL credentials obtained from ``client_cert_source``.
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = ClientOptions.from_dict(client_options)
+ if client_options is None:
+ client_options = ClientOptions.ClientOptions()
+
+ if client_options.api_endpoint is None:
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never")
+ if use_mtls_env == "never":
+ client_options.api_endpoint = self.DEFAULT_ENDPOINT
+ elif use_mtls_env == "always":
+ client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ elif use_mtls_env == "auto":
+ has_client_cert_source = (
+ client_options.client_cert_source is not None
+ or mtls.has_default_client_cert_source()
+ )
+ client_options.api_endpoint = (
+ self.DEFAULT_MTLS_ENDPOINT
+ if has_client_cert_source
+ else self.DEFAULT_ENDPOINT
+ )
+ else:
+ raise MutualTLSChannelError(
+ "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always"
+ )
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, RealmsServiceTransport):
# transport is a RealmsServiceTransport instance.
- if credentials:
+ if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
+ if client_options.scopes:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its scopes directly."
+ )
self._transport = transport
- elif client_options is None or (
- client_options.api_endpoint is None
- and client_options.client_cert_source is None
- ):
- # Don't trigger mTLS if we get an empty ClientOptions.
+ else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
- credentials=credentials, host=self.DEFAULT_ENDPOINT
- )
- else:
- # We have a non-empty ClientOptions. If client_cert_source is
- # provided, trigger mTLS with user provided endpoint or the default
- # mTLS endpoint.
- if client_options.client_cert_source:
- api_mtls_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_MTLS_ENDPOINT
- )
- else:
- api_mtls_endpoint = None
-
- api_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_ENDPOINT
- )
-
- self._transport = RealmsServiceGrpcTransport(
credentials=credentials,
- host=api_endpoint,
- api_mtls_endpoint=api_mtls_endpoint,
+ credentials_file=client_options.credentials_file,
+ host=client_options.api_endpoint,
+ scopes=client_options.scopes,
+ api_mtls_endpoint=client_options.api_endpoint,
client_cert_source=client_options.client_cert_source,
)
@@ -232,7 +248,7 @@ def list_realms(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListRealmsPager:
- r"""Lists Realms in a given project and Location.
+ r"""Lists realms in a given project and location.
Args:
request (:class:`~.realms.ListRealmsRequest`):
@@ -280,7 +296,7 @@ def list_realms(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
- self._transport.list_realms, default_timeout=None, client_info=_client_info
+ self._transport.list_realms, default_timeout=None, client_info=_client_info,
)
# Certain fields should be provided within the metadata header;
@@ -290,12 +306,12 @@ def list_realms(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListRealmsPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -310,14 +326,14 @@ def get_realm(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> realms.Realm:
- r"""Gets details of a single Realm.
+ r"""Gets details of a single realm.
Args:
request (:class:`~.realms.GetRealmRequest`):
The request object. Request message for
RealmsService.GetRealm.
name (:class:`str`):
- Required. The name of the Realm to retrieve. Uses the
+ Required. The name of the realm to retrieve. Uses the
form:
``projects/{project}/locations/{location}/realms/{realm}``.
This corresponds to the ``name`` field
@@ -332,7 +348,7 @@ def get_realm(
Returns:
~.realms.Realm:
- A Realm resource.
+ A realm resource.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
@@ -354,7 +370,7 @@ def get_realm(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
- self._transport.get_realm, default_timeout=None, client_info=_client_info
+ self._transport.get_realm, default_timeout=None, client_info=_client_info,
)
# Certain fields should be provided within the metadata header;
@@ -364,7 +380,7 @@ def get_realm(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -380,7 +396,7 @@ def create_realm(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Creates a new Realm in a given project and Location.
+ r"""Creates a new realm in a given project and location.
Args:
request (:class:`~.realms.CreateRealmRequest`):
@@ -393,13 +409,13 @@ def create_realm(
on the ``request`` instance; if ``request`` is provided, this
should not be set.
realm (:class:`~.realms.Realm`):
- Required. The Realm resource to be
+ Required. The realm resource to be
created.
This corresponds to the ``realm`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
realm_id (:class:`str`):
- Required. The ID of the Realm
+ Required. The ID of the realm
resource to be created.
This corresponds to the ``realm_id`` field
on the ``request`` instance; if ``request`` is provided, this
@@ -416,7 +432,7 @@ def create_realm(
An object representing a long-running operation.
The result type for the operation will be
- :class:``~.realms.Realm``: A Realm resource.
+ :class:``~.realms.Realm``: A realm resource.
"""
# Create or coerce a protobuf request object.
@@ -443,11 +459,19 @@ def create_realm(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
- self._transport.create_realm, default_timeout=None, client_info=_client_info
+ self._transport.create_realm,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -469,14 +493,14 @@ def delete_realm(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Deletes a single Realm.
+ r"""Deletes a single realm.
Args:
request (:class:`~.realms.DeleteRealmRequest`):
The request object. Request message for
RealmsService.DeleteRealm.
name (:class:`str`):
- Required. The name of the Realm to delete. Uses the
+ Required. The name of the realm to delete. Uses the
form:
``projects/{project}/locations/{location}/realms/{realm}``.
This corresponds to the ``name`` field
@@ -494,7 +518,20 @@ def delete_realm(
An object representing a long-running operation.
The result type for the operation will be
- :class:``~.realms.Realm``: A Realm resource.
+ :class:``~.empty.Empty``: A generic empty message that
+ you can re-use to avoid defining duplicated empty
+ messages in your APIs. A typical example is to use it as
+ the request or the response type of an API method. For
+ instance:
+
+ ::
+
+ service Foo {
+ rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ }
+
+ The JSON representation for ``Empty`` is empty JSON
+ object ``{}``.
"""
# Create or coerce a protobuf request object.
@@ -517,17 +554,25 @@ def delete_realm(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
- self._transport.delete_realm, default_timeout=None, client_info=_client_info
+ self._transport.delete_realm,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
response,
self._transport.operations_client,
- realms.Realm,
+ empty.Empty,
metadata_type=common.OperationMetadata,
)
@@ -544,14 +589,14 @@ def update_realm(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation.Operation:
- r"""Patches a single Realm.
+ r"""Patches a single realm.
Args:
request (:class:`~.realms.UpdateRealmRequest`):
The request object. Request message for
RealmsService.UpdateRealm.
realm (:class:`~.realms.Realm`):
- Required. The Realm to be updated. Only fields specified
+ Required. The realm to be updated. Only fields specified
in update_mask are updated.
This corresponds to the ``realm`` field
on the ``request`` instance; if ``request`` is provided, this
@@ -577,7 +622,7 @@ def update_realm(
An object representing a long-running operation.
The result type for the operation will be
- :class:``~.realms.Realm``: A Realm resource.
+ :class:``~.realms.Realm``: A realm resource.
"""
# Create or coerce a protobuf request object.
@@ -602,11 +647,21 @@ def update_realm(
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
- self._transport.update_realm, default_timeout=None, client_info=_client_info
+ self._transport.update_realm,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("realm.name", request.realm.name),)
+ ),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation.from_gapic(
@@ -627,7 +682,7 @@ def preview_realm_update(
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> realms.PreviewRealmUpdateResponse:
- r"""Previews patches to a single Realm.
+ r"""Previews patches to a single realm.
Args:
request (:class:`~.realms.PreviewRealmUpdateRequest`):
@@ -658,8 +713,16 @@ def preview_realm_update(
client_info=_client_info,
)
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("realm.name", request.realm.name),)
+ ),
+ )
+
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -668,8 +731,8 @@ def preview_realm_update(
try:
_client_info = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
- "google-cloud-game-servers"
- ).version
+ "google-cloud-game-servers",
+ ).version,
)
except pkg_resources.DistributionNotFound:
_client_info = gapic_v1.client_info.ClientInfo()
diff --git a/google/cloud/gaming_v1/services/realms_service/pagers.py b/google/cloud/gaming_v1/services/realms_service/pagers.py
index 82516a2f..2d93adc0 100644
--- a/google/cloud/gaming_v1/services/realms_service/pagers.py
+++ b/google/cloud/gaming_v1/services/realms_service/pagers.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-from typing import Any, Callable, Iterable
+from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
from google.cloud.gaming_v1.types import realms
@@ -40,9 +40,11 @@ class ListRealmsPager:
def __init__(
self,
- method: Callable[[realms.ListRealmsRequest], realms.ListRealmsResponse],
+ method: Callable[..., realms.ListRealmsResponse],
request: realms.ListRealmsRequest,
response: realms.ListRealmsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -53,10 +55,13 @@ def __init__(
The initial request object.
response (:class:`~.realms.ListRealmsResponse`):
The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
"""
self._method = method
self._request = realms.ListRealmsRequest(request)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@@ -66,7 +71,7 @@ def pages(self) -> Iterable[realms.ListRealmsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[realms.Realm]:
@@ -75,3 +80,69 @@ def __iter__(self) -> Iterable[realms.Realm]:
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class ListRealmsAsyncPager:
+ """A pager for iterating through ``list_realms`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.realms.ListRealmsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``realms`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListRealms`` requests and continue to iterate
+ through the ``realms`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.realms.ListRealmsResponse`
+ attributes are available on the pager. If multiple requests are made, only
+ the most recent response is retained, and thus used for attribute lookup.
+ """
+
+ def __init__(
+ self,
+ method: Callable[..., Awaitable[realms.ListRealmsResponse]],
+ request: realms.ListRealmsRequest,
+ response: realms.ListRealmsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.realms.ListRealmsRequest`):
+ The initial request object.
+ response (:class:`~.realms.ListRealmsResponse`):
+ The initial response object.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ self._method = method
+ self._request = realms.ListRealmsRequest(request)
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(self) -> AsyncIterable[realms.ListRealmsResponse]:
+ yield self._response
+ while self._response.next_page_token:
+ self._request.page_token = self._response.next_page_token
+ self._response = await self._method(self._request, metadata=self._metadata)
+ yield self._response
+
+ def __aiter__(self) -> AsyncIterable[realms.Realm]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.realms:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
diff --git a/google/cloud/gaming_v1/services/realms_service/transports/__init__.py b/google/cloud/gaming_v1/services/realms_service/transports/__init__.py
index 532d3b69..2b139b78 100644
--- a/google/cloud/gaming_v1/services/realms_service/transports/__init__.py
+++ b/google/cloud/gaming_v1/services/realms_service/transports/__init__.py
@@ -20,11 +20,17 @@
from .base import RealmsServiceTransport
from .grpc import RealmsServiceGrpcTransport
+from .grpc_asyncio import RealmsServiceGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[RealmsServiceTransport]]
_transport_registry["grpc"] = RealmsServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = RealmsServiceGrpcAsyncIOTransport
-__all__ = ("RealmsServiceTransport", "RealmsServiceGrpcTransport")
+__all__ = (
+ "RealmsServiceTransport",
+ "RealmsServiceGrpcTransport",
+ "RealmsServiceGrpcAsyncIOTransport",
+)
diff --git a/google/cloud/gaming_v1/services/realms_service/transports/base.py b/google/cloud/gaming_v1/services/realms_service/transports/base.py
index e38f3920..33b97793 100644
--- a/google/cloud/gaming_v1/services/realms_service/transports/base.py
+++ b/google/cloud/gaming_v1/services/realms_service/transports/base.py
@@ -19,6 +19,7 @@
import typing
from google import auth
+from google.api_core import exceptions # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.auth import credentials # type: ignore
@@ -26,7 +27,7 @@
from google.longrunning import operations_pb2 as operations # type: ignore
-class RealmsServiceTransport(metaclass=abc.ABCMeta):
+class RealmsServiceTransport(abc.ABC):
"""Abstract transport class for RealmsService."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
@@ -36,6 +37,9 @@ def __init__(
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: typing.Optional[str] = None,
+ scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
+ **kwargs,
) -> None:
"""Instantiate the transport.
@@ -46,6 +50,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scope (Optional[Sequence[str]]): A list of scopes.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
@@ -54,8 +62,17 @@ def __init__(
# If no credentials are provided, then determine the appropriate
# defaults.
- if credentials is None:
- credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+ if credentials and credentials_file:
+ raise exceptions.DuplicateCredentialArgs(
+ "'credentials_file' and 'credentials' are mutually exclusive"
+ )
+
+ if credentials_file is not None:
+ credentials, _ = auth.load_credentials_from_file(
+ credentials_file, scopes=scopes
+ )
+ elif credentials is None:
+ credentials, _ = auth.default(scopes=scopes)
# Save the credentials.
self._credentials = credentials
@@ -63,43 +80,66 @@ def __init__(
@property
def operations_client(self) -> operations_v1.OperationsClient:
"""Return the client designed to process long-running operations."""
- raise NotImplementedError
+ raise NotImplementedError()
@property
def list_realms(
- self
- ) -> typing.Callable[[realms.ListRealmsRequest], realms.ListRealmsResponse]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [realms.ListRealmsRequest],
+ typing.Union[
+ realms.ListRealmsResponse, typing.Awaitable[realms.ListRealmsResponse]
+ ],
+ ]:
+ raise NotImplementedError()
@property
- def get_realm(self) -> typing.Callable[[realms.GetRealmRequest], realms.Realm]:
- raise NotImplementedError
+ def get_realm(
+ self,
+ ) -> typing.Callable[
+ [realms.GetRealmRequest],
+ typing.Union[realms.Realm, typing.Awaitable[realms.Realm]],
+ ]:
+ raise NotImplementedError()
@property
def create_realm(
- self
- ) -> typing.Callable[[realms.CreateRealmRequest], operations.Operation]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [realms.CreateRealmRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ ]:
+ raise NotImplementedError()
@property
def delete_realm(
- self
- ) -> typing.Callable[[realms.DeleteRealmRequest], operations.Operation]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [realms.DeleteRealmRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ ]:
+ raise NotImplementedError()
@property
def update_realm(
- self
- ) -> typing.Callable[[realms.UpdateRealmRequest], operations.Operation]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [realms.UpdateRealmRequest],
+ typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ ]:
+ raise NotImplementedError()
@property
def preview_realm_update(
- self
+ self,
) -> typing.Callable[
- [realms.PreviewRealmUpdateRequest], realms.PreviewRealmUpdateResponse
+ [realms.PreviewRealmUpdateRequest],
+ typing.Union[
+ realms.PreviewRealmUpdateResponse,
+ typing.Awaitable[realms.PreviewRealmUpdateResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
__all__ = ("RealmsServiceTransport",)
diff --git a/google/cloud/gaming_v1/services/realms_service/transports/grpc.py b/google/cloud/gaming_v1/services/realms_service/transports/grpc.py
index 2774b4bd..d4095864 100644
--- a/google/cloud/gaming_v1/services/realms_service/transports/grpc.py
+++ b/google/cloud/gaming_v1/services/realms_service/transports/grpc.py
@@ -15,10 +15,11 @@
# limitations under the License.
#
-from typing import Callable, Dict, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
+from google import auth # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
@@ -34,7 +35,7 @@
class RealmsServiceGrpcTransport(RealmsServiceTransport):
"""gRPC backend transport for RealmsService.
- A Realm is a grouping of Game Server Clusters that are
+ A realm is a grouping of game server clusters that are
considered interchangeable.
This class defines the same methods as the primary client, so the
@@ -45,11 +46,15 @@ class RealmsServiceGrpcTransport(RealmsServiceTransport):
top of HTTP/2); the ``grpcio`` package must be installed.
"""
+ _stubs: Dict[str, Callable]
+
def __init__(
self,
*,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
@@ -64,6 +69,11 @@ def __init__(
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
+ ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
@@ -76,8 +86,10 @@ def __init__(
is None.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
if channel:
# Sanity check: Ensure that channel and credentials are not both
@@ -93,6 +105,9 @@ def __init__(
else api_mtls_endpoint + ":443"
)
+ if credentials is None:
+ credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
@@ -104,15 +119,22 @@ def __init__(
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
- self._grpc_channel = grpc_helpers.create_channel(
+ self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
+ credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
- scopes=self.AUTH_SCOPES,
+ scopes=scopes or self.AUTH_SCOPES,
)
# Run the base constructor.
- super().__init__(host=host, credentials=credentials)
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
self._stubs = {} # type: Dict[str, Callable]
@classmethod
@@ -120,6 +142,8 @@ def create_channel(
cls,
host: str = "gameservices.googleapis.com",
credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Optional[Sequence[str]] = None,
**kwargs
) -> grpc.Channel:
"""Create and return a gRPC channel object.
@@ -130,13 +154,28 @@ def create_channel(
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
+
+ Raises:
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
"""
+ scopes = scopes or cls.AUTH_SCOPES
return grpc_helpers.create_channel(
- host, credentials=credentials, scopes=cls.AUTH_SCOPES, **kwargs
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
)
@property
@@ -150,7 +189,7 @@ def grpc_channel(self) -> grpc.Channel:
# have one.
if not hasattr(self, "_grpc_channel"):
self._grpc_channel = self.create_channel(
- self._host, credentials=self._credentials
+ self._host, credentials=self._credentials,
)
# Return the channel from cache.
@@ -174,11 +213,11 @@ def operations_client(self) -> operations_v1.OperationsClient:
@property
def list_realms(
- self
+ self,
) -> Callable[[realms.ListRealmsRequest], realms.ListRealmsResponse]:
r"""Return a callable for the list realms method over gRPC.
- Lists Realms in a given project and Location.
+ Lists realms in a given project and location.
Returns:
Callable[[~.ListRealmsRequest],
@@ -202,7 +241,7 @@ def list_realms(
def get_realm(self) -> Callable[[realms.GetRealmRequest], realms.Realm]:
r"""Return a callable for the get realm method over gRPC.
- Gets details of a single Realm.
+ Gets details of a single realm.
Returns:
Callable[[~.GetRealmRequest],
@@ -224,11 +263,11 @@ def get_realm(self) -> Callable[[realms.GetRealmRequest], realms.Realm]:
@property
def create_realm(
- self
+ self,
) -> Callable[[realms.CreateRealmRequest], operations.Operation]:
r"""Return a callable for the create realm method over gRPC.
- Creates a new Realm in a given project and Location.
+ Creates a new realm in a given project and location.
Returns:
Callable[[~.CreateRealmRequest],
@@ -250,11 +289,11 @@ def create_realm(
@property
def delete_realm(
- self
+ self,
) -> Callable[[realms.DeleteRealmRequest], operations.Operation]:
r"""Return a callable for the delete realm method over gRPC.
- Deletes a single Realm.
+ Deletes a single realm.
Returns:
Callable[[~.DeleteRealmRequest],
@@ -276,11 +315,11 @@ def delete_realm(
@property
def update_realm(
- self
+ self,
) -> Callable[[realms.UpdateRealmRequest], operations.Operation]:
r"""Return a callable for the update realm method over gRPC.
- Patches a single Realm.
+ Patches a single realm.
Returns:
Callable[[~.UpdateRealmRequest],
@@ -302,13 +341,13 @@ def update_realm(
@property
def preview_realm_update(
- self
+ self,
) -> Callable[
[realms.PreviewRealmUpdateRequest], realms.PreviewRealmUpdateResponse
]:
r"""Return a callable for the preview realm update method over gRPC.
- Previews patches to a single Realm.
+ Previews patches to a single realm.
Returns:
Callable[[~.PreviewRealmUpdateRequest],
diff --git a/google/cloud/gaming_v1/services/realms_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1/services/realms_service/transports/grpc_asyncio.py
new file mode 100644
index 00000000..d0f618c3
--- /dev/null
+++ b/google/cloud/gaming_v1/services/realms_service/transports/grpc_asyncio.py
@@ -0,0 +1,366 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+
+from google.api_core import grpc_helpers_async # type: ignore
+from google.api_core import operations_v1 # type: ignore
+from google.auth import credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+
+import grpc # type: ignore
+from grpc.experimental import aio # type: ignore
+
+from google.cloud.gaming_v1.types import realms
+from google.longrunning import operations_pb2 as operations # type: ignore
+
+from .base import RealmsServiceTransport
+from .grpc import RealmsServiceGrpcTransport
+
+
+class RealmsServiceGrpcAsyncIOTransport(RealmsServiceTransport):
+ """gRPC AsyncIO backend transport for RealmsService.
+
+ A realm is a grouping of game server clusters that are
+ considered interchangeable.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends protocol buffers over the wire using gRPC (which is built on
+ top of HTTP/2); the ``grpcio`` package must be installed.
+ """
+
+ _grpc_channel: aio.Channel
+ _stubs: Dict[str, Callable] = {}
+
+ @classmethod
+ def create_channel(
+ cls,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ **kwargs
+ ) -> aio.Channel:
+ """Create and return a gRPC AsyncIO channel object.
+ Args:
+ address (Optional[str]): The host for the channel to use.
+ credentials (Optional[~.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify this application to the service. If
+ none are specified, the client will attempt to ascertain
+ the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
+ channel creation.
+ Returns:
+ aio.Channel: A gRPC AsyncIO channel object.
+ """
+ scopes = scopes or cls.AUTH_SCOPES
+ return grpc_helpers_async.create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ **kwargs
+ )
+
+ def __init__(
+ self,
+ *,
+ host: str = "gameservices.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ channel: aio.Channel = None,
+ api_mtls_endpoint: str = None,
+ client_cert_source: Callable[[], Tuple[bytes, bytes]] = None
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]): The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ channel (Optional[aio.Channel]): A ``Channel`` instance through
+ which to make calls.
+ api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
+ provided, it overrides the ``host`` argument and tries to create
+ a mutual TLS channel with client SSL credentials from
+ ``client_cert_source`` or applicatin default SSL credentials.
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
+ callback to provide client SSL certificate bytes and private key
+ bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
+ is None.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
+ """
+ if channel:
+ # Sanity check: Ensure that channel and credentials are not both
+ # provided.
+ credentials = False
+
+ # If a channel was explicitly provided, set it.
+ self._grpc_channel = channel
+ elif api_mtls_endpoint:
+ host = (
+ api_mtls_endpoint
+ if ":" in api_mtls_endpoint
+ else api_mtls_endpoint + ":443"
+ )
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ ssl_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ ssl_credentials = SslCredentials().ssl_credentials
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ # Run the base constructor.
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ )
+
+ self._stubs = {}
+
+ @property
+ def grpc_channel(self) -> aio.Channel:
+ """Create the channel designed to connect to this service.
+
+ This property caches on the instance; repeated calls return
+ the same channel.
+ """
+ # Sanity check: Only create a new channel if we do not already
+ # have one.
+ if not hasattr(self, "_grpc_channel"):
+ self._grpc_channel = self.create_channel(
+ self._host, credentials=self._credentials,
+ )
+
+ # Return the channel from cache.
+ return self._grpc_channel
+
+ @property
+ def operations_client(self) -> operations_v1.OperationsAsyncClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Sanity check: Only create a new client if we do not already have one.
+ if "operations_client" not in self.__dict__:
+ self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient(
+ self.grpc_channel
+ )
+
+ # Return the client from cache.
+ return self.__dict__["operations_client"]
+
+ @property
+ def list_realms(
+ self,
+ ) -> Callable[[realms.ListRealmsRequest], Awaitable[realms.ListRealmsResponse]]:
+ r"""Return a callable for the list realms method over gRPC.
+
+ Lists realms in a given project and location.
+
+ Returns:
+ Callable[[~.ListRealmsRequest],
+ Awaitable[~.ListRealmsResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "list_realms" not in self._stubs:
+ self._stubs["list_realms"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.RealmsService/ListRealms",
+ request_serializer=realms.ListRealmsRequest.serialize,
+ response_deserializer=realms.ListRealmsResponse.deserialize,
+ )
+ return self._stubs["list_realms"]
+
+ @property
+ def get_realm(self) -> Callable[[realms.GetRealmRequest], Awaitable[realms.Realm]]:
+ r"""Return a callable for the get realm method over gRPC.
+
+ Gets details of a single realm.
+
+ Returns:
+ Callable[[~.GetRealmRequest],
+ Awaitable[~.Realm]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_realm" not in self._stubs:
+ self._stubs["get_realm"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.RealmsService/GetRealm",
+ request_serializer=realms.GetRealmRequest.serialize,
+ response_deserializer=realms.Realm.deserialize,
+ )
+ return self._stubs["get_realm"]
+
+ @property
+ def create_realm(
+ self,
+ ) -> Callable[[realms.CreateRealmRequest], Awaitable[operations.Operation]]:
+ r"""Return a callable for the create realm method over gRPC.
+
+ Creates a new realm in a given project and location.
+
+ Returns:
+ Callable[[~.CreateRealmRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "create_realm" not in self._stubs:
+ self._stubs["create_realm"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.RealmsService/CreateRealm",
+ request_serializer=realms.CreateRealmRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["create_realm"]
+
+ @property
+ def delete_realm(
+ self,
+ ) -> Callable[[realms.DeleteRealmRequest], Awaitable[operations.Operation]]:
+ r"""Return a callable for the delete realm method over gRPC.
+
+ Deletes a single realm.
+
+ Returns:
+ Callable[[~.DeleteRealmRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_realm" not in self._stubs:
+ self._stubs["delete_realm"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.RealmsService/DeleteRealm",
+ request_serializer=realms.DeleteRealmRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["delete_realm"]
+
+ @property
+ def update_realm(
+ self,
+ ) -> Callable[[realms.UpdateRealmRequest], Awaitable[operations.Operation]]:
+ r"""Return a callable for the update realm method over gRPC.
+
+ Patches a single realm.
+
+ Returns:
+ Callable[[~.UpdateRealmRequest],
+ Awaitable[~.Operation]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "update_realm" not in self._stubs:
+ self._stubs["update_realm"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.RealmsService/UpdateRealm",
+ request_serializer=realms.UpdateRealmRequest.serialize,
+ response_deserializer=operations.Operation.FromString,
+ )
+ return self._stubs["update_realm"]
+
+ @property
+ def preview_realm_update(
+ self,
+ ) -> Callable[
+ [realms.PreviewRealmUpdateRequest], Awaitable[realms.PreviewRealmUpdateResponse]
+ ]:
+ r"""Return a callable for the preview realm update method over gRPC.
+
+ Previews patches to a single realm.
+
+ Returns:
+ Callable[[~.PreviewRealmUpdateRequest],
+ Awaitable[~.PreviewRealmUpdateResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "preview_realm_update" not in self._stubs:
+ self._stubs["preview_realm_update"] = self.grpc_channel.unary_unary(
+ "/google.cloud.gaming.v1beta.RealmsService/PreviewRealmUpdate",
+ request_serializer=realms.PreviewRealmUpdateRequest.serialize,
+ response_deserializer=realms.PreviewRealmUpdateResponse.deserialize,
+ )
+ return self._stubs["preview_realm_update"]
+
+
+__all__ = ("RealmsServiceGrpcAsyncIOTransport",)
diff --git a/google/cloud/gaming_v1/types/__init__.py b/google/cloud/gaming_v1/types/__init__.py
index 28428851..20d3e075 100644
--- a/google/cloud/gaming_v1/types/__init__.py
+++ b/google/cloud/gaming_v1/types/__init__.py
@@ -36,6 +36,23 @@
FleetConfig,
GameServerConfig,
)
+from .game_server_deployments import (
+ ListGameServerDeploymentsRequest,
+ ListGameServerDeploymentsResponse,
+ GetGameServerDeploymentRequest,
+ GetGameServerDeploymentRolloutRequest,
+ CreateGameServerDeploymentRequest,
+ DeleteGameServerDeploymentRequest,
+ UpdateGameServerDeploymentRequest,
+ UpdateGameServerDeploymentRolloutRequest,
+ FetchDeploymentStateRequest,
+ FetchDeploymentStateResponse,
+ GameServerDeployment,
+ GameServerConfigOverride,
+ GameServerDeploymentRollout,
+ PreviewGameServerDeploymentRolloutRequest,
+ PreviewGameServerDeploymentRolloutResponse,
+)
from .realms import (
ListRealmsRequest,
ListRealmsResponse,
@@ -64,23 +81,6 @@
GkeClusterReference,
GameServerCluster,
)
-from .game_server_deployments import (
- ListGameServerDeploymentsRequest,
- ListGameServerDeploymentsResponse,
- GetGameServerDeploymentRequest,
- GetGameServerDeploymentRolloutRequest,
- CreateGameServerDeploymentRequest,
- DeleteGameServerDeploymentRequest,
- UpdateGameServerDeploymentRequest,
- UpdateGameServerDeploymentRolloutRequest,
- FetchDeploymentStateRequest,
- FetchDeploymentStateResponse,
- GameServerDeployment,
- GameServerConfigOverride,
- GameServerDeploymentRollout,
- PreviewGameServerDeploymentRolloutRequest,
- PreviewGameServerDeploymentRolloutResponse,
-)
__all__ = (
@@ -101,6 +101,21 @@
"ScalingConfig",
"FleetConfig",
"GameServerConfig",
+ "ListGameServerDeploymentsRequest",
+ "ListGameServerDeploymentsResponse",
+ "GetGameServerDeploymentRequest",
+ "GetGameServerDeploymentRolloutRequest",
+ "CreateGameServerDeploymentRequest",
+ "DeleteGameServerDeploymentRequest",
+ "UpdateGameServerDeploymentRequest",
+ "UpdateGameServerDeploymentRolloutRequest",
+ "FetchDeploymentStateRequest",
+ "FetchDeploymentStateResponse",
+ "GameServerDeployment",
+ "GameServerConfigOverride",
+ "GameServerDeploymentRollout",
+ "PreviewGameServerDeploymentRolloutRequest",
+ "PreviewGameServerDeploymentRolloutResponse",
"ListRealmsRequest",
"ListRealmsResponse",
"GetRealmRequest",
@@ -125,19 +140,4 @@
"GameServerClusterConnectionInfo",
"GkeClusterReference",
"GameServerCluster",
- "ListGameServerDeploymentsRequest",
- "ListGameServerDeploymentsResponse",
- "GetGameServerDeploymentRequest",
- "GetGameServerDeploymentRolloutRequest",
- "CreateGameServerDeploymentRequest",
- "DeleteGameServerDeploymentRequest",
- "UpdateGameServerDeploymentRequest",
- "UpdateGameServerDeploymentRolloutRequest",
- "FetchDeploymentStateRequest",
- "FetchDeploymentStateResponse",
- "GameServerDeployment",
- "GameServerConfigOverride",
- "GameServerDeploymentRollout",
- "PreviewGameServerDeploymentRolloutRequest",
- "PreviewGameServerDeploymentRolloutResponse",
)
diff --git a/google/cloud/gaming_v1/types/common.py b/google/cloud/gaming_v1/types/common.py
index 758c8ec6..839ca1d7 100644
--- a/google/cloud/gaming_v1/types/common.py
+++ b/google/cloud/gaming_v1/types/common.py
@@ -70,24 +70,32 @@ class OperationMetadata(proto.Message):
Output only. List of Locations that could not
be reached.
operation_status (Sequence[~.common.OperationMetadata.OperationStatusEntry]):
- Output only. Operation status for
- gameservices API operations. Operation status is
- in the form of key-value pairs where keys are
+ Output only. Operation status for Game
+ Services API operations. Operation status is in
+ the form of key-value pairs where keys are
resource IDs and the values show the status of
the operation. In case of failures, the value
includes an error code and error message.
"""
- create_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp)
- end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
+ create_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,)
+
+ end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
target = proto.Field(proto.STRING, number=3)
+
verb = proto.Field(proto.STRING, number=4)
+
status_message = proto.Field(proto.STRING, number=5)
+
requested_cancellation = proto.Field(proto.BOOL, number=6)
+
api_version = proto.Field(proto.STRING, number=7)
+
unreachable = proto.RepeatedField(proto.STRING, number=8)
+
operation_status = proto.MapField(
- proto.STRING, proto.MESSAGE, number=9, message="OperationStatus"
+ proto.STRING, proto.MESSAGE, number=9, message="OperationStatus",
)
@@ -112,7 +120,9 @@ class ErrorCode(proto.Enum):
CLUSTER_CONNECTION = 3
done = proto.Field(proto.BOOL, number=1)
- error_code = proto.Field(proto.ENUM, number=2, enum=ErrorCode)
+
+ error_code = proto.Field(proto.ENUM, number=2, enum=ErrorCode,)
+
error_message = proto.Field(proto.STRING, number=3)
@@ -128,11 +138,11 @@ class LabelSelector(proto.Message):
class RealmSelector(proto.Message):
- r"""The Realm selector, used to match Realm resources.
+ r"""The realm selector, used to match realm resources.
Attributes:
realms (Sequence[str]):
- List of Realms to match.
+ List of realms to match.
"""
realms = proto.RepeatedField(proto.STRING, number=1)
@@ -165,12 +175,15 @@ class Schedule(proto.Message):
The cron definition of the scheduled event.
See https://en.wikipedia.org/wiki/Cron. Cron
spec specifies the local time as defined by the
- Realm.
+ realm.
"""
- start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp)
- end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
- cron_job_duration = proto.Field(proto.MESSAGE, number=3, message=duration.Duration)
+ start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,)
+
+ end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
+ cron_job_duration = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,)
+
cron_spec = proto.Field(proto.STRING, number=4)
@@ -180,7 +193,7 @@ class SpecSource(proto.Message):
Attributes:
game_server_config_name (str):
- The Game Server Config resource. Uses the form:
+ The game server config resource. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}/configs/{config_id}``.
name (str):
@@ -190,6 +203,7 @@ class SpecSource(proto.Message):
"""
game_server_config_name = proto.Field(proto.STRING, number=1)
+
name = proto.Field(proto.STRING, number=2)
@@ -198,16 +212,16 @@ class TargetDetails(proto.Message):
Attributes:
game_server_cluster_name (str):
- The Game Server Cluster name. Uses the form:
+ The game server cluster name. Uses the form:
``projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}``.
game_server_deployment_name (str):
- The Game Server Deployment name. Uses the form:
+ The game server deployment name. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}``.
fleet_details (Sequence[~.common.TargetDetails.TargetFleetDetails]):
- Agones fleet details for Game Server Clusters
- and Game Server Deployments.
+ Agones fleet details for game server clusters
+ and game server deployments.
"""
class TargetFleetDetails(proto.Message):
@@ -233,7 +247,8 @@ class TargetFleet(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
- spec_source = proto.Field(proto.MESSAGE, number=2, message=SpecSource)
+
+ spec_source = proto.Field(proto.MESSAGE, number=2, message=SpecSource,)
class TargetFleetAutoscaler(proto.Message):
r"""Target Agones autoscaler policy reference.
@@ -247,13 +262,15 @@ class TargetFleetAutoscaler(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
- spec_source = proto.Field(proto.MESSAGE, number=2, message=SpecSource)
+
+ spec_source = proto.Field(proto.MESSAGE, number=2, message=SpecSource,)
fleet = proto.Field(
proto.MESSAGE,
number=1,
message="TargetDetails.TargetFleetDetails.TargetFleet",
)
+
autoscaler = proto.Field(
proto.MESSAGE,
number=2,
@@ -261,9 +278,11 @@ class TargetFleetAutoscaler(proto.Message):
)
game_server_cluster_name = proto.Field(proto.STRING, number=1)
+
game_server_deployment_name = proto.Field(proto.STRING, number=2)
+
fleet_details = proto.RepeatedField(
- proto.MESSAGE, number=3, message=TargetFleetDetails
+ proto.MESSAGE, number=3, message=TargetFleetDetails,
)
@@ -275,7 +294,7 @@ class TargetState(proto.Message):
Details about Agones fleets.
"""
- details = proto.RepeatedField(proto.MESSAGE, number=1, message=TargetDetails)
+ details = proto.RepeatedField(proto.MESSAGE, number=1, message=TargetDetails,)
class DeployedFleetDetails(proto.Message):
@@ -330,13 +349,19 @@ class DeployedFleetStatus(proto.Message):
"""
ready_replicas = proto.Field(proto.INT64, number=1)
+
allocated_replicas = proto.Field(proto.INT64, number=2)
+
reserved_replicas = proto.Field(proto.INT64, number=3)
+
replicas = proto.Field(proto.INT64, number=4)
fleet = proto.Field(proto.STRING, number=1)
+
fleet_spec = proto.Field(proto.STRING, number=2)
- spec_source = proto.Field(proto.MESSAGE, number=3, message=SpecSource)
+
+ spec_source = proto.Field(proto.MESSAGE, number=3, message=SpecSource,)
+
status = proto.Field(
proto.MESSAGE,
number=5,
@@ -358,12 +383,15 @@ class DeployedFleetAutoscaler(proto.Message):
"""
autoscaler = proto.Field(proto.STRING, number=1)
- spec_source = proto.Field(proto.MESSAGE, number=4, message=SpecSource)
+
+ spec_source = proto.Field(proto.MESSAGE, number=4, message=SpecSource,)
+
fleet_autoscaler_spec = proto.Field(proto.STRING, number=3)
- deployed_fleet = proto.Field(proto.MESSAGE, number=1, message=DeployedFleet)
+ deployed_fleet = proto.Field(proto.MESSAGE, number=1, message=DeployedFleet,)
+
deployed_autoscaler = proto.Field(
- proto.MESSAGE, number=2, message=DeployedFleetAutoscaler
+ proto.MESSAGE, number=2, message=DeployedFleetAutoscaler,
)
diff --git a/google/cloud/gaming_v1/types/game_server_clusters.py b/google/cloud/gaming_v1/types/game_server_clusters.py
index 0ff93c44..05f88b09 100644
--- a/google/cloud/gaming_v1/types/game_server_clusters.py
+++ b/google/cloud/gaming_v1/types/game_server_clusters.py
@@ -56,9 +56,9 @@ class ListGameServerClustersRequest(proto.Message):
"projects/{project}/locations/{location}/realms/{realm}".
page_size (int):
Optional. The maximum number of items to return. If
- unspecified, server will pick an appropriate default. Server
- may return fewer items than requested. A caller should only
- rely on response's
+ unspecified, the server will pick an appropriate default.
+ The server may return fewer items than requested. A caller
+ should only rely on response's
[next_page_token][google.cloud.gaming.v1beta.ListGameServerClustersResponse.next_page_token]
to determine if there are more GameServerClusters left to be
queried.
@@ -75,9 +75,13 @@ class ListGameServerClustersRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
page_size = proto.Field(proto.INT32, number=2)
+
page_token = proto.Field(proto.STRING, number=3)
+
filter = proto.Field(proto.STRING, number=4)
+
order_by = proto.Field(proto.STRING, number=5)
@@ -87,13 +91,13 @@ class ListGameServerClustersResponse(proto.Message):
Attributes:
game_server_clusters (Sequence[~.gcgv_game_server_clusters.GameServerCluster]):
- The list of Game Server Clusters.
+ The list of game server clusters.
next_page_token (str):
Token to retrieve the next page of results,
or empty if there are no more results in the
list.
unreachable (Sequence[str]):
- List of Locations that could not be reached.
+ List of locations that could not be reached.
"""
@property
@@ -101,9 +105,11 @@ def raw_page(self):
return self
game_server_clusters = proto.RepeatedField(
- proto.MESSAGE, number=1, message="GameServerCluster"
+ proto.MESSAGE, number=1, message="GameServerCluster",
)
+
next_page_token = proto.Field(proto.STRING, number=2)
+
unreachable = proto.RepeatedField(proto.STRING, number=4)
@@ -113,7 +119,7 @@ class GetGameServerClusterRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Cluster to retrieve.
+ Required. The name of the game server cluster to retrieve.
Uses the form:
``projects/{project}/locations/{location}/realms/{realm-id}/gameServerClusters/{cluster}``.
@@ -131,17 +137,19 @@ class CreateGameServerClusterRequest(proto.Message):
Required. The parent resource name. Uses the form:
``projects/{project}/locations/{location}/realms/{realm-id}``.
game_server_cluster_id (str):
- Required. The ID of the Game Server Cluster
+ Required. The ID of the game server cluster
resource to be created.
game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster):
- Required. The Game Server Cluster resource to
+ Required. The game server cluster resource to
be created.
"""
parent = proto.Field(proto.STRING, number=1)
+
game_server_cluster_id = proto.Field(proto.STRING, number=2)
+
game_server_cluster = proto.Field(
- proto.MESSAGE, number=3, message="GameServerCluster"
+ proto.MESSAGE, number=3, message="GameServerCluster",
)
@@ -154,10 +162,10 @@ class PreviewCreateGameServerClusterRequest(proto.Message):
Required. The parent resource name. Uses the form:
``projects/{project}/locations/{location}/realms/{realm}``.
game_server_cluster_id (str):
- Required. The ID of the Game Server Cluster
+ Required. The ID of the game server cluster
resource to be created.
game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster):
- Required. The Game Server Cluster resource to
+ Required. The game server cluster resource to
be created.
preview_time (~.timestamp.Timestamp):
Optional. The target timestamp to compute the
@@ -165,11 +173,14 @@ class PreviewCreateGameServerClusterRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
game_server_cluster_id = proto.Field(proto.STRING, number=2)
+
game_server_cluster = proto.Field(
- proto.MESSAGE, number=3, message="GameServerCluster"
+ proto.MESSAGE, number=3, message="GameServerCluster",
)
- preview_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp)
+
+ preview_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,)
class PreviewCreateGameServerClusterResponse(proto.Message):
@@ -184,7 +195,8 @@ class PreviewCreateGameServerClusterResponse(proto.Message):
"""
etag = proto.Field(proto.STRING, number=2)
- target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState)
+
+ target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,)
class DeleteGameServerClusterRequest(proto.Message):
@@ -193,7 +205,7 @@ class DeleteGameServerClusterRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Cluster to delete.
+ Required. The name of the game server cluster to delete.
Uses the form:
``projects/{project}/locations/{location}/gameServerClusters/{cluster}``.
"""
@@ -207,7 +219,7 @@ class PreviewDeleteGameServerClusterRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Cluster to delete.
+ Required. The name of the game server cluster to delete.
Uses the form:
``projects/{project}/locations/{location}/gameServerClusters/{cluster}``.
preview_time (~.timestamp.Timestamp):
@@ -216,7 +228,8 @@ class PreviewDeleteGameServerClusterRequest(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
- preview_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
+
+ preview_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
class PreviewDeleteGameServerClusterResponse(proto.Message):
@@ -231,7 +244,8 @@ class PreviewDeleteGameServerClusterResponse(proto.Message):
"""
etag = proto.Field(proto.STRING, number=2)
- target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState)
+
+ target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,)
class UpdateGameServerClusterRequest(proto.Message):
@@ -240,7 +254,7 @@ class UpdateGameServerClusterRequest(proto.Message):
Attributes:
game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster):
- Required. The Game Server Cluster to be updated. Only fields
+ Required. The game server cluster to be updated. Only fields
specified in update_mask are updated.
update_mask (~.field_mask.FieldMask):
Required. Mask of fields to update. At least one path must
@@ -252,9 +266,10 @@ class UpdateGameServerClusterRequest(proto.Message):
"""
game_server_cluster = proto.Field(
- proto.MESSAGE, number=1, message="GameServerCluster"
+ proto.MESSAGE, number=1, message="GameServerCluster",
)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
class PreviewUpdateGameServerClusterRequest(proto.Message):
@@ -263,7 +278,7 @@ class PreviewUpdateGameServerClusterRequest(proto.Message):
Attributes:
game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster):
- Required. The Game Server Cluster to be updated. Only fields
+ Required. The game server cluster to be updated. Only fields
specified in update_mask are updated.
update_mask (~.field_mask.FieldMask):
Required. Mask of fields to update. At least one path must
@@ -278,10 +293,12 @@ class PreviewUpdateGameServerClusterRequest(proto.Message):
"""
game_server_cluster = proto.Field(
- proto.MESSAGE, number=1, message="GameServerCluster"
+ proto.MESSAGE, number=1, message="GameServerCluster",
)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
- preview_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+
+ preview_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
class PreviewUpdateGameServerClusterResponse(proto.Message):
@@ -296,26 +313,31 @@ class PreviewUpdateGameServerClusterResponse(proto.Message):
"""
etag = proto.Field(proto.STRING, number=2)
- target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState)
+
+ target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,)
class GameServerClusterConnectionInfo(proto.Message):
- r"""The Game Server Cluster connection information.
+ r"""The game server cluster connection information.
Attributes:
gke_cluster_reference (~.gcgv_game_server_clusters.GkeClusterReference):
Reference to the GKE cluster where the game
servers are installed.
namespace (str):
- Namespace designated on the Game Server
- Cluster where the Agones game server instances
+ Namespace designated on the game server
+ cluster where the Agones game server instances
will be created. Existence of the namespace will
be validated during creation.
"""
gke_cluster_reference = proto.Field(
- proto.MESSAGE, number=7, message="GkeClusterReference"
+ proto.MESSAGE,
+ number=7,
+ oneof="cluster_reference",
+ message="GkeClusterReference",
)
+
namespace = proto.Field(proto.STRING, number=5)
@@ -339,11 +361,11 @@ class GkeClusterReference(proto.Message):
class GameServerCluster(proto.Message):
- r"""A Game Server Cluster resource.
+ r"""A game server cluster resource.
Attributes:
name (str):
- Required. The resource name of the Game Server Cluster. Uses
+ Required. The resource name of the game server cluster. Uses
the form:
``projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}``.
@@ -355,12 +377,12 @@ class GameServerCluster(proto.Message):
update_time (~.timestamp.Timestamp):
Output only. The last-modified time.
labels (Sequence[~.gcgv_game_server_clusters.GameServerCluster.LabelsEntry]):
- The labels associated with this Game Server
- Cluster. Each label is a key-value pair.
+ The labels associated with this game server
+ cluster. Each label is a key-value pair.
connection_info (~.gcgv_game_server_clusters.GameServerClusterConnectionInfo):
- Game Server Cluster connection information.
- This information is used to manage Game Server
- Clusters.
+ The game server cluster connection
+ information. This information is used to manage
+ game server clusters.
etag (str):
ETag of the resource.
description (str):
@@ -368,13 +390,19 @@ class GameServerCluster(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
- create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
- update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+
+ create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
+ update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
+
labels = proto.MapField(proto.STRING, proto.STRING, number=4)
+
connection_info = proto.Field(
- proto.MESSAGE, number=5, message=GameServerClusterConnectionInfo
+ proto.MESSAGE, number=5, message=GameServerClusterConnectionInfo,
)
+
etag = proto.Field(proto.STRING, number=6)
+
description = proto.Field(proto.STRING, number=7)
diff --git a/google/cloud/gaming_v1/types/game_server_clusters_service.py b/google/cloud/gaming_v1/types/game_server_clusters_service.py
index 7ab431d6..87138f5c 100644
--- a/google/cloud/gaming_v1/types/game_server_clusters_service.py
+++ b/google/cloud/gaming_v1/types/game_server_clusters_service.py
@@ -16,7 +16,7 @@
#
-__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={})
+__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/gaming_v1/types/game_server_configs.py b/google/cloud/gaming_v1/types/game_server_configs.py
index 4584c97c..6f0ebc3d 100644
--- a/google/cloud/gaming_v1/types/game_server_configs.py
+++ b/google/cloud/gaming_v1/types/game_server_configs.py
@@ -56,7 +56,7 @@ class ListGameServerConfigsRequest(proto.Message):
queried.
page_token (str):
Optional. The next_page_token value returned from a previous
- List request, if any.
+ list request, if any.
filter (str):
Optional. The filter to apply to list
results.
@@ -67,9 +67,13 @@ class ListGameServerConfigsRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
page_size = proto.Field(proto.INT32, number=2)
+
page_token = proto.Field(proto.STRING, number=3)
+
filter = proto.Field(proto.STRING, number=4)
+
order_by = proto.Field(proto.STRING, number=5)
@@ -79,13 +83,13 @@ class ListGameServerConfigsResponse(proto.Message):
Attributes:
game_server_configs (Sequence[~.gcgv_game_server_configs.GameServerConfig]):
- The list of Game Server Configs.
+ The list of game server configs.
next_page_token (str):
Token to retrieve the next page of results,
or empty if there are no more results in the
list.
unreachable (Sequence[str]):
- List of Locations that could not be reached.
+ List of locations that could not be reached.
"""
@property
@@ -93,9 +97,11 @@ def raw_page(self):
return self
game_server_configs = proto.RepeatedField(
- proto.MESSAGE, number=1, message="GameServerConfig"
+ proto.MESSAGE, number=1, message="GameServerConfig",
)
+
next_page_token = proto.Field(proto.STRING, number=2)
+
unreachable = proto.RepeatedField(proto.STRING, number=4)
@@ -105,7 +111,7 @@ class GetGameServerConfigRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Config to retrieve.
+ Required. The name of the game server config to retrieve.
Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``.
@@ -124,17 +130,19 @@ class CreateGameServerConfigRequest(proto.Message):
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/``.
config_id (str):
- Required. The ID of the Game Server Config
+ Required. The ID of the game server config
resource to be created.
game_server_config (~.gcgv_game_server_configs.GameServerConfig):
- Required. The Game Server Config resource to
+ Required. The game server config resource to
be created.
"""
parent = proto.Field(proto.STRING, number=1)
+
config_id = proto.Field(proto.STRING, number=2)
+
game_server_config = proto.Field(
- proto.MESSAGE, number=3, message="GameServerConfig"
+ proto.MESSAGE, number=3, message="GameServerConfig",
)
@@ -144,7 +152,7 @@ class DeleteGameServerConfigRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Config to delete. Uses
+ Required. The name of the game server config to delete. Uses
the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``.
@@ -164,9 +172,9 @@ class ScalingConfig(proto.Message):
Example spec:
https://agones.dev/site/docs/reference/fleetautoscaler/
selectors (Sequence[~.common.LabelSelector]):
- Labels used to identify the Game Server
- Clusters to which this Agones scaling config
- applies. A Game Server Cluster is subject to
+ Labels used to identify the game server
+ clusters to which this Agones scaling config
+ applies. A game server cluster is subject to
this Agones scaling config if its labels match
any of the selector entries.
schedules (Sequence[~.common.Schedule]):
@@ -175,11 +183,14 @@ class ScalingConfig(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
+
fleet_autoscaler_spec = proto.Field(proto.STRING, number=2)
+
selectors = proto.RepeatedField(
- proto.MESSAGE, number=4, message=common.LabelSelector
+ proto.MESSAGE, number=4, message=common.LabelSelector,
)
- schedules = proto.RepeatedField(proto.MESSAGE, number=5, message=common.Schedule)
+
+ schedules = proto.RepeatedField(proto.MESSAGE, number=5, message=common.Schedule,)
class FleetConfig(proto.Message):
@@ -194,15 +205,16 @@ class FleetConfig(proto.Message):
"""
fleet_spec = proto.Field(proto.STRING, number=1)
+
name = proto.Field(proto.STRING, number=2)
class GameServerConfig(proto.Message):
- r"""A Game Server Config resource.
+ r"""A game server config resource.
Attributes:
name (str):
- The resource name of the Game Server Config. Uses the form:
+ The resource name of the game server config. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``.
For example,
@@ -213,25 +225,31 @@ class GameServerConfig(proto.Message):
update_time (~.timestamp.Timestamp):
Output only. The last-modified time.
labels (Sequence[~.gcgv_game_server_configs.GameServerConfig.LabelsEntry]):
- The labels associated with this Game Server
- Config. Each label is a key-value pair.
+ The labels associated with this game server
+ config. Each label is a key-value pair.
fleet_configs (Sequence[~.gcgv_game_server_configs.FleetConfig]):
FleetConfig contains a list of Agones fleet
specs. Only one FleetConfig is allowed.
scaling_configs (Sequence[~.gcgv_game_server_configs.ScalingConfig]):
The autoscaling settings.
description (str):
- The description of the Game Server Config.
+ The description of the game server config.
"""
name = proto.Field(proto.STRING, number=1)
- create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
- update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+
+ create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
+ update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
+
labels = proto.MapField(proto.STRING, proto.STRING, number=4)
- fleet_configs = proto.RepeatedField(proto.MESSAGE, number=5, message=FleetConfig)
+
+ fleet_configs = proto.RepeatedField(proto.MESSAGE, number=5, message=FleetConfig,)
+
scaling_configs = proto.RepeatedField(
- proto.MESSAGE, number=6, message=ScalingConfig
+ proto.MESSAGE, number=6, message=ScalingConfig,
)
+
description = proto.Field(proto.STRING, number=7)
diff --git a/google/cloud/gaming_v1/types/game_server_configs_service.py b/google/cloud/gaming_v1/types/game_server_configs_service.py
index 7ab431d6..87138f5c 100644
--- a/google/cloud/gaming_v1/types/game_server_configs_service.py
+++ b/google/cloud/gaming_v1/types/game_server_configs_service.py
@@ -16,7 +16,7 @@
#
-__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={})
+__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/gaming_v1/types/game_server_deployments.py b/google/cloud/gaming_v1/types/game_server_deployments.py
index 79620f5a..6e7db91b 100644
--- a/google/cloud/gaming_v1/types/game_server_deployments.py
+++ b/google/cloud/gaming_v1/types/game_server_deployments.py
@@ -55,9 +55,9 @@ class ListGameServerDeploymentsRequest(proto.Message):
``projects/{project}/locations/{location}``.
page_size (int):
Optional. The maximum number of items to return. If
- unspecified, server will pick an appropriate default. Server
- may return fewer items than requested. A caller should only
- rely on response's
+ unspecified, the server will pick an appropriate default.
+ The server may return fewer items than requested. A caller
+ should only rely on response's
[next_page_token][google.cloud.gaming.v1beta.ListGameServerDeploymentsResponse.next_page_token]
to determine if there are more GameServerDeployments left to
be queried.
@@ -74,9 +74,13 @@ class ListGameServerDeploymentsRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
page_size = proto.Field(proto.INT32, number=2)
+
page_token = proto.Field(proto.STRING, number=3)
+
filter = proto.Field(proto.STRING, number=4)
+
order_by = proto.Field(proto.STRING, number=5)
@@ -86,13 +90,13 @@ class ListGameServerDeploymentsResponse(proto.Message):
Attributes:
game_server_deployments (Sequence[~.gcgv_game_server_deployments.GameServerDeployment]):
- The list of Game Server Delpoyments.
+ The list of game server deployments.
next_page_token (str):
Token to retrieve the next page of results,
or empty if there are no more results in the
list.
unreachable (Sequence[str]):
- List of Locations that could not be reached.
+ List of locations that could not be reached.
"""
@property
@@ -100,9 +104,11 @@ def raw_page(self):
return self
game_server_deployments = proto.RepeatedField(
- proto.MESSAGE, number=1, message="GameServerDeployment"
+ proto.MESSAGE, number=1, message="GameServerDeployment",
)
+
next_page_token = proto.Field(proto.STRING, number=2)
+
unreachable = proto.RepeatedField(proto.STRING, number=4)
@@ -112,7 +118,7 @@ class GetGameServerDeploymentRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Deployment to
+ Required. The name of the game server delpoyment to
retrieve. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
@@ -127,7 +133,7 @@ class GetGameServerDeploymentRolloutRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Deployment to
+ Required. The name of the game server delpoyment to
retrieve. Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout``.
@@ -145,17 +151,19 @@ class CreateGameServerDeploymentRequest(proto.Message):
Required. The parent resource name. Uses the form:
``projects/{project}/locations/{location}``.
deployment_id (str):
- Required. The ID of the Game Server
- Deployment resource to be created.
+ Required. The ID of the game server
+ delpoyment resource to be created.
game_server_deployment (~.gcgv_game_server_deployments.GameServerDeployment):
- Required. The Game Server Deployment resource
+ Required. The game server delpoyment resource
to be created.
"""
parent = proto.Field(proto.STRING, number=1)
+
deployment_id = proto.Field(proto.STRING, number=2)
+
game_server_deployment = proto.Field(
- proto.MESSAGE, number=3, message="GameServerDeployment"
+ proto.MESSAGE, number=3, message="GameServerDeployment",
)
@@ -165,7 +173,7 @@ class DeleteGameServerDeploymentRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Deployment to delete.
+ Required. The name of the game server delpoyment to delete.
Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
@@ -181,7 +189,7 @@ class UpdateGameServerDeploymentRequest(proto.Message):
Attributes:
game_server_deployment (~.gcgv_game_server_deployments.GameServerDeployment):
- Required. The Game Server Deployment to be updated. Only
+ Required. The game server delpoyment to be updated. Only
fields specified in update_mask are updated.
update_mask (~.field_mask.FieldMask):
Required. Mask of fields to update. At least one path must
@@ -193,9 +201,10 @@ class UpdateGameServerDeploymentRequest(proto.Message):
"""
game_server_deployment = proto.Field(
- proto.MESSAGE, number=1, message="GameServerDeployment"
+ proto.MESSAGE, number=1, message="GameServerDeployment",
)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
class UpdateGameServerDeploymentRolloutRequest(proto.Message):
@@ -204,7 +213,7 @@ class UpdateGameServerDeploymentRolloutRequest(proto.Message):
Attributes:
rollout (~.gcgv_game_server_deployments.GameServerDeploymentRollout):
- Required. The Game Server Deployment Rollout to be updated.
+ Required. The game server delpoyment rollout to be updated.
Only fields specified in update_mask are updated.
update_mask (~.field_mask.FieldMask):
Required. Mask of fields to update. At least one path must
@@ -216,9 +225,10 @@ class UpdateGameServerDeploymentRolloutRequest(proto.Message):
"""
rollout = proto.Field(
- proto.MESSAGE, number=1, message="GameServerDeploymentRollout"
+ proto.MESSAGE, number=1, message="GameServerDeploymentRollout",
)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
class FetchDeploymentStateRequest(proto.Message):
@@ -227,7 +237,7 @@ class FetchDeploymentStateRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Game Server Deployment. Uses the
+ Required. The name of the game server delpoyment. Uses the
form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
@@ -242,41 +252,43 @@ class FetchDeploymentStateResponse(proto.Message):
Attributes:
cluster_state (Sequence[~.gcgv_game_server_deployments.FetchDeploymentStateResponse.DeployedClusterState]):
- The state of the Game Server Deployment in
- each Game Server Cluster.
+ The state of the game server deployment in
+ each game server cluster.
unavailable (Sequence[str]):
- List of Locations that could not be reached.
+ List of locations that could not be reached.
"""
class DeployedClusterState(proto.Message):
- r"""The Game Server Cluster changes made by the Game Server
- Deployment.
+ r"""The game server cluster changes made by the game server
+ deployment.
Attributes:
cluster (str):
The name of the cluster.
fleet_details (Sequence[~.common.DeployedFleetDetails]):
The details about the Agones fleets and
- autoscalers created in the Game Server Cluster.
+ autoscalers created in the game server cluster.
"""
cluster = proto.Field(proto.STRING, number=1)
+
fleet_details = proto.RepeatedField(
- proto.MESSAGE, number=2, message=common.DeployedFleetDetails
+ proto.MESSAGE, number=2, message=common.DeployedFleetDetails,
)
cluster_state = proto.RepeatedField(
- proto.MESSAGE, number=1, message=DeployedClusterState
+ proto.MESSAGE, number=1, message=DeployedClusterState,
)
+
unavailable = proto.RepeatedField(proto.STRING, number=2)
class GameServerDeployment(proto.Message):
- r"""A Game Server Deployment resource.
+ r"""A game server deployment resource.
Attributes:
name (str):
- The resource name of the Game Server Deployment. Uses the
+ The resource name of the game server deployment. Uses the
form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``.
@@ -288,25 +300,30 @@ class GameServerDeployment(proto.Message):
update_time (~.timestamp.Timestamp):
Output only. The last-modified time.
labels (Sequence[~.gcgv_game_server_deployments.GameServerDeployment.LabelsEntry]):
- The labels associated with this Game Server
- Deployment. Each label is a key-value pair.
+ The labels associated with this game server
+ deployment. Each label is a key-value pair.
etag (str):
ETag of the resource.
description (str):
- Human readable description of the Game Server
- Deployment.
+ Human readable description of the game server
+ delpoyment.
"""
name = proto.Field(proto.STRING, number=1)
- create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
- update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+
+ create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
+ update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
+
labels = proto.MapField(proto.STRING, proto.STRING, number=4)
+
etag = proto.Field(proto.STRING, number=7)
+
description = proto.Field(proto.STRING, number=8)
class GameServerConfigOverride(proto.Message):
- r"""A Game Server Config override.
+ r"""A game server config override.
Attributes:
realms_selector (~.common.RealmSelector):
@@ -315,17 +332,20 @@ class GameServerConfigOverride(proto.Message):
The game server config for this override.
"""
- realms_selector = proto.Field(proto.MESSAGE, number=1, message=common.RealmSelector)
- config_version = proto.Field(proto.STRING, number=100)
+ realms_selector = proto.Field(
+ proto.MESSAGE, number=1, oneof="selector", message=common.RealmSelector,
+ )
+
+ config_version = proto.Field(proto.STRING, number=100, oneof="change")
class GameServerDeploymentRollout(proto.Message):
- r"""The Game Server Deployment Rollout which represents the
+ r"""The game server deployment rollout which represents the
desired rollout state.
Attributes:
name (str):
- The resource name of the Game Server Deployment Rollout.
+ The resource name of the game server deployment rollout.
Uses the form:
``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout``.
@@ -337,26 +357,31 @@ class GameServerDeploymentRollout(proto.Message):
update_time (~.timestamp.Timestamp):
Output only. The last-modified time.
default_game_server_config (str):
- The default Game Server Config is applied to all Realms
- unless overridden in the Rollout. For example,
+ The default game server config is applied to all realms
+ unless overridden in the rollout. For example,
``projects/my-project/locations/global/gameServerDeployments/my-game/configs/my-config``.
game_server_config_overrides (Sequence[~.gcgv_game_server_deployments.GameServerConfigOverride]):
- Contains the Game Server Config Rollout
+ Contains the game server config rollout
overrides. Overrides are processed in the order
they are listed. Once a match is found for a
- Realm, the rest of the list is not processed.
+ realm, the rest of the list is not processed.
etag (str):
ETag of the resource.
"""
name = proto.Field(proto.STRING, number=1)
- create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
- update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+
+ create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
+ update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
+
default_game_server_config = proto.Field(proto.STRING, number=4)
+
game_server_config_overrides = proto.RepeatedField(
- proto.MESSAGE, number=5, message=GameServerConfigOverride
+ proto.MESSAGE, number=5, message=GameServerConfigOverride,
)
+
etag = proto.Field(proto.STRING, number=6)
@@ -365,7 +390,7 @@ class PreviewGameServerDeploymentRolloutRequest(proto.Message):
Attributes:
rollout (~.gcgv_game_server_deployments.GameServerDeploymentRollout):
- Required. The Game Server Deployment Rollout to be updated.
+ Required. The game server deployment rollout to be updated.
Only fields specified in update_mask are updated.
update_mask (~.field_mask.FieldMask):
Optional. Mask of fields to update. At least one path must
@@ -377,12 +402,14 @@ class PreviewGameServerDeploymentRolloutRequest(proto.Message):
preview_time (~.timestamp.Timestamp):
Optional. The target timestamp to compute the
preview. Defaults to the immediately after the
- proposed Rollout completes.
+ proposed rollout completes.
"""
- rollout = proto.Field(proto.MESSAGE, number=1, message=GameServerDeploymentRollout)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
- preview_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+ rollout = proto.Field(proto.MESSAGE, number=1, message=GameServerDeploymentRollout,)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+
+ preview_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
class PreviewGameServerDeploymentRolloutResponse(proto.Message):
@@ -395,14 +422,16 @@ class PreviewGameServerDeploymentRolloutResponse(proto.Message):
Locations that could not be reached on this
request.
etag (str):
- ETag of the Game Server Deployment.
+ ETag of the game server deployment.
target_state (~.common.TargetState):
The target state.
"""
unavailable = proto.RepeatedField(proto.STRING, number=2)
+
etag = proto.Field(proto.STRING, number=3)
- target_state = proto.Field(proto.MESSAGE, number=4, message=common.TargetState)
+
+ target_state = proto.Field(proto.MESSAGE, number=4, message=common.TargetState,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/gaming_v1/types/game_server_deployments_service.py b/google/cloud/gaming_v1/types/game_server_deployments_service.py
index 7ab431d6..87138f5c 100644
--- a/google/cloud/gaming_v1/types/game_server_deployments_service.py
+++ b/google/cloud/gaming_v1/types/game_server_deployments_service.py
@@ -16,7 +16,7 @@
#
-__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={})
+__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/gaming_v1/types/realms.py b/google/cloud/gaming_v1/types/realms.py
index 2ea694b6..78a54833 100644
--- a/google/cloud/gaming_v1/types/realms.py
+++ b/google/cloud/gaming_v1/types/realms.py
@@ -52,7 +52,7 @@ class ListRealmsRequest(proto.Message):
may return fewer items than requested. A caller should only
rely on response's
[next_page_token][google.cloud.gaming.v1beta.ListRealmsResponse.next_page_token]
- to determine if there are more Realms left to be queried.
+ to determine if there are more realms left to be queried.
page_token (str):
Optional. The next_page_token value returned from a previous
List request, if any.
@@ -66,9 +66,13 @@ class ListRealmsRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
page_size = proto.Field(proto.INT32, number=2)
+
page_token = proto.Field(proto.STRING, number=3)
+
filter = proto.Field(proto.STRING, number=4)
+
order_by = proto.Field(proto.STRING, number=5)
@@ -77,21 +81,23 @@ class ListRealmsResponse(proto.Message):
Attributes:
realms (Sequence[~.gcgv_realms.Realm]):
- The list of Realms.
+ The list of realms.
next_page_token (str):
Token to retrieve the next page of results,
or empty if there are no more results in the
list.
unreachable (Sequence[str]):
- List of Locations that could not be reached.
+ List of locations that could not be reached.
"""
@property
def raw_page(self):
return self
- realms = proto.RepeatedField(proto.MESSAGE, number=1, message="Realm")
+ realms = proto.RepeatedField(proto.MESSAGE, number=1, message="Realm",)
+
next_page_token = proto.Field(proto.STRING, number=2)
+
unreachable = proto.RepeatedField(proto.STRING, number=3)
@@ -100,7 +106,7 @@ class GetRealmRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Realm to retrieve. Uses the form:
+ Required. The name of the realm to retrieve. Uses the form:
``projects/{project}/locations/{location}/realms/{realm}``.
"""
@@ -115,15 +121,17 @@ class CreateRealmRequest(proto.Message):
Required. The parent resource name. Uses the form:
``projects/{project}/locations/{location}``.
realm_id (str):
- Required. The ID of the Realm resource to be
+ Required. The ID of the realm resource to be
created.
realm (~.gcgv_realms.Realm):
- Required. The Realm resource to be created.
+ Required. The realm resource to be created.
"""
parent = proto.Field(proto.STRING, number=1)
+
realm_id = proto.Field(proto.STRING, number=2)
- realm = proto.Field(proto.MESSAGE, number=3, message="Realm")
+
+ realm = proto.Field(proto.MESSAGE, number=3, message="Realm",)
class DeleteRealmRequest(proto.Message):
@@ -131,7 +139,7 @@ class DeleteRealmRequest(proto.Message):
Attributes:
name (str):
- Required. The name of the Realm to delete. Uses the form:
+ Required. The name of the realm to delete. Uses the form:
``projects/{project}/locations/{location}/realms/{realm}``.
"""
@@ -143,7 +151,7 @@ class UpdateRealmRequest(proto.Message):
Attributes:
realm (~.gcgv_realms.Realm):
- Required. The Realm to be updated. Only fields specified in
+ Required. The realm to be updated. Only fields specified in
update_mask are updated.
update_mask (~.field_mask.FieldMask):
Required. The update mask applies to the resource. For the
@@ -153,8 +161,9 @@ class UpdateRealmRequest(proto.Message):
/docs/reference/google.protobuf#fieldmask
"""
- realm = proto.Field(proto.MESSAGE, number=1, message="Realm")
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
+ realm = proto.Field(proto.MESSAGE, number=1, message="Realm",)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
class PreviewRealmUpdateRequest(proto.Message):
@@ -162,7 +171,7 @@ class PreviewRealmUpdateRequest(proto.Message):
Attributes:
realm (~.gcgv_realms.Realm):
- Required. The Realm to be updated. Only fields specified in
+ Required. The realm to be updated. Only fields specified in
update_mask are updated.
update_mask (~.field_mask.FieldMask):
Required. The update mask applies to the resource. For the
@@ -175,9 +184,11 @@ class PreviewRealmUpdateRequest(proto.Message):
preview.
"""
- realm = proto.Field(proto.MESSAGE, number=1, message="Realm")
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
- preview_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+ realm = proto.Field(proto.MESSAGE, number=1, message="Realm",)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+
+ preview_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
class PreviewRealmUpdateResponse(proto.Message):
@@ -191,15 +202,16 @@ class PreviewRealmUpdateResponse(proto.Message):
"""
etag = proto.Field(proto.STRING, number=2)
- target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState)
+
+ target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,)
class Realm(proto.Message):
- r"""A Realm resource.
+ r"""A realm resource.
Attributes:
name (str):
- The resource name of the Realm. Uses the form:
+ The resource name of the realm. Uses the form:
``projects/{project}/locations/{location}/realms/{realm}``.
For example,
``projects/my-project/locations/{location}/realms/my-realm``.
@@ -208,25 +220,31 @@ class Realm(proto.Message):
update_time (~.timestamp.Timestamp):
Output only. The last-modified time.
labels (Sequence[~.gcgv_realms.Realm.LabelsEntry]):
- The labels associated with this Realm. Each
+ The labels associated with this realm. Each
label is a key-value pair.
time_zone (str):
Required. Time zone where all policies
- targeting this Realm are evaluated. The value of
+ targeting this realm are evaluated. The value of
this field must be from the IANA time zone
database: https://www.iana.org/time-zones.
etag (str):
ETag of the resource.
description (str):
- Human readable description of the Realm.
+ Human readable description of the realm.
"""
name = proto.Field(proto.STRING, number=1)
- create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp)
- update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+
+ create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+
+ update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
+
labels = proto.MapField(proto.STRING, proto.STRING, number=4)
+
time_zone = proto.Field(proto.STRING, number=6)
+
etag = proto.Field(proto.STRING, number=7)
+
description = proto.Field(proto.STRING, number=8)
diff --git a/google/cloud/gaming_v1/types/realms_service.py b/google/cloud/gaming_v1/types/realms_service.py
index 7ab431d6..87138f5c 100644
--- a/google/cloud/gaming_v1/types/realms_service.py
+++ b/google/cloud/gaming_v1/types/realms_service.py
@@ -16,7 +16,7 @@
#
-__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={})
+__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/noxfile.py b/noxfile.py
index 64d8340e..d191708d 100644
--- a/noxfile.py
+++ b/noxfile.py
@@ -23,14 +23,15 @@
import nox
-BLACK_VERSION = "black==19.3b0"
+BLACK_VERSION = "black==19.10b0"
BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"]
-if os.path.exists("samples"):
- BLACK_PATHS.append("samples")
+DEFAULT_PYTHON_VERSION = "3.8"
+SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"]
+UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"]
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint(session):
"""Run linters.
@@ -38,7 +39,9 @@ def lint(session):
serious code quality issues.
"""
session.install("flake8", BLACK_VERSION)
- session.run("black", "--check", *BLACK_PATHS)
+ session.run(
+ "black", "--check", *BLACK_PATHS,
+ )
session.run("flake8", "google", "tests")
@@ -53,10 +56,12 @@ def blacken(session):
check the state of the `gcp_ubuntu_config` we use for that Kokoro run.
"""
session.install(BLACK_VERSION)
- session.run("black", *BLACK_PATHS)
+ session.run(
+ "black", *BLACK_PATHS,
+ )
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint_setup_py(session):
"""Verify that setup.py is valid (including RST check)."""
session.install("docutils", "pygments")
@@ -65,6 +70,8 @@ def lint_setup_py(session):
def default(session):
# Install all test dependencies, then install this package in-place.
+ session.install("asyncmock", "pytest-asyncio")
+
session.install("mock", "pytest", "pytest-cov")
session.install("-e", ".")
@@ -84,13 +91,13 @@ def default(session):
)
-@nox.session(python=["3.6", "3.7", "3.8"])
+@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)
def unit(session):
"""Run the unit test suite."""
default(session)
-@nox.session(python=["3.7"])
+@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS)
def system(session):
"""Run the system test suite."""
system_test_path = os.path.join("tests", "system.py")
@@ -110,7 +117,9 @@ def system(session):
# Install all test dependencies, then install this package into the
# virtualenv's dist-packages.
- session.install("mock", "pytest", "google-cloud-testutils")
+ session.install(
+ "mock", "pytest", "google-cloud-testutils",
+ )
session.install("-e", ".")
# Run py.test against the system tests.
@@ -120,7 +129,7 @@ def system(session):
session.run("py.test", "--quiet", system_test_folder_path, *session.posargs)
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def cover(session):
"""Run the final coverage report.
@@ -133,7 +142,7 @@ def cover(session):
session.run("coverage", "erase")
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def docs(session):
"""Build the docs for this library."""
diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh
new file mode 100755
index 00000000..ff599eb2
--- /dev/null
+++ b/scripts/decrypt-secrets.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+# Copyright 2015 Google Inc. 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.
+# 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.
+
+DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+ROOT=$( dirname "$DIR" )
+
+# Work from the project root.
+cd $ROOT
+
+# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources.
+PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}"
+
+gcloud secrets versions access latest --secret="python-docs-samples-test-env" \
+ > testing/test-env.sh
+gcloud secrets versions access latest \
+ --secret="python-docs-samples-service-account" \
+ > testing/service-account.json
+gcloud secrets versions access latest \
+ --secret="python-docs-samples-client-secrets" \
+ > testing/client-secrets.json
\ No newline at end of file
diff --git a/scripts/fixup_gaming_v1_keywords.py b/scripts/fixup_gaming_v1_keywords.py
new file mode 100644
index 00000000..3a315945
--- /dev/null
+++ b/scripts/fixup_gaming_v1_keywords.py
@@ -0,0 +1,203 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import argparse
+import os
+import libcst as cst
+import pathlib
+import sys
+from typing import (Any, Callable, Dict, List, Sequence, Tuple)
+
+
+def partition(
+ predicate: Callable[[Any], bool],
+ iterator: Sequence[Any]
+) -> Tuple[List[Any], List[Any]]:
+ """A stable, out-of-place partition."""
+ results = ([], [])
+
+ for i in iterator:
+ results[int(predicate(i))].append(i)
+
+ # Returns trueList, falseList
+ return results[1], results[0]
+
+
+class gamingCallTransformer(cst.CSTTransformer):
+ CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
+ METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
+ 'create_game_server_cluster': ('parent', 'game_server_cluster_id', 'game_server_cluster', ),
+ 'create_game_server_config': ('parent', 'config_id', 'game_server_config', ),
+ 'create_game_server_deployment': ('parent', 'deployment_id', 'game_server_deployment', ),
+ 'create_realm': ('parent', 'realm_id', 'realm', ),
+ 'delete_game_server_cluster': ('name', ),
+ 'delete_game_server_config': ('name', ),
+ 'delete_game_server_deployment': ('name', ),
+ 'delete_realm': ('name', ),
+ 'fetch_deployment_state': ('name', ),
+ 'get_game_server_cluster': ('name', ),
+ 'get_game_server_config': ('name', ),
+ 'get_game_server_deployment': ('name', ),
+ 'get_game_server_deployment_rollout': ('name', ),
+ 'get_realm': ('name', ),
+ 'list_game_server_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ),
+ 'list_game_server_configs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ),
+ 'list_game_server_deployments': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ),
+ 'list_realms': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ),
+ 'preview_create_game_server_cluster': ('parent', 'game_server_cluster_id', 'game_server_cluster', 'preview_time', ),
+ 'preview_delete_game_server_cluster': ('name', 'preview_time', ),
+ 'preview_game_server_deployment_rollout': ('rollout', 'update_mask', 'preview_time', ),
+ 'preview_realm_update': ('realm', 'update_mask', 'preview_time', ),
+ 'preview_update_game_server_cluster': ('game_server_cluster', 'update_mask', 'preview_time', ),
+ 'update_game_server_cluster': ('game_server_cluster', 'update_mask', ),
+ 'update_game_server_deployment': ('game_server_deployment', 'update_mask', ),
+ 'update_game_server_deployment_rollout': ('rollout', 'update_mask', ),
+ 'update_realm': ('realm', 'update_mask', ),
+ }
+
+ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
+ try:
+ key = original.func.attr.value
+ kword_params = self.METHOD_TO_PARAMS[key]
+ except (AttributeError, KeyError):
+ # Either not a method from the API or too convoluted to be sure.
+ return updated
+
+ # If the existing code is valid, keyword args come after positional args.
+ # Therefore, all positional args must map to the first parameters.
+ args, kwargs = partition(lambda a: not bool(a.keyword), updated.args)
+ if any(k.keyword.value == "request" for k in kwargs):
+ # We've already fixed this file, don't fix it again.
+ return updated
+
+ kwargs, ctrl_kwargs = partition(
+ lambda a: not a.keyword.value in self.CTRL_PARAMS,
+ kwargs
+ )
+
+ args, ctrl_args = args[:len(kword_params)], args[len(kword_params):]
+ ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
+ for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))
+
+ request_arg = cst.Arg(
+ value=cst.Dict([
+ cst.DictElement(
+ cst.SimpleString("'{}'".format(name)),
+ cst.Element(value=arg.value)
+ )
+ # Note: the args + kwargs looks silly, but keep in mind that
+ # the control parameters had to be stripped out, and that
+ # those could have been passed positionally or by keyword.
+ for name, arg in zip(kword_params, args + kwargs)]),
+ keyword=cst.Name("request")
+ )
+
+ return updated.with_changes(
+ args=[request_arg] + ctrl_kwargs
+ )
+
+
+def fix_files(
+ in_dir: pathlib.Path,
+ out_dir: pathlib.Path,
+ *,
+ transformer=gamingCallTransformer(),
+):
+ """Duplicate the input dir to the output dir, fixing file method calls.
+
+ Preconditions:
+ * in_dir is a real directory
+ * out_dir is a real, empty directory
+ """
+ pyfile_gen = (
+ pathlib.Path(os.path.join(root, f))
+ for root, _, files in os.walk(in_dir)
+ for f in files if os.path.splitext(f)[1] == ".py"
+ )
+
+ for fpath in pyfile_gen:
+ with open(fpath, 'r') as f:
+ src = f.read()
+
+ # Parse the code and insert method call fixes.
+ tree = cst.parse_module(src)
+ updated = tree.visit(transformer)
+
+ # Create the path and directory structure for the new file.
+ updated_path = out_dir.joinpath(fpath.relative_to(in_dir))
+ updated_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # Generate the updated source file at the corresponding path.
+ with open(updated_path, 'w') as f:
+ f.write(updated.code)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(
+ description="""Fix up source that uses the gaming client library.
+
+The existing sources are NOT overwritten but are copied to output_dir with changes made.
+
+Note: This tool operates at a best-effort level at converting positional
+ parameters in client method calls to keyword based parameters.
+ Cases where it WILL FAIL include
+ A) * or ** expansion in a method call.
+ B) Calls via function or method alias (includes free function calls)
+ C) Indirect or dispatched calls (e.g. the method is looked up dynamically)
+
+ These all constitute false negatives. The tool will also detect false
+ positives when an API method shares a name with another method.
+""")
+ parser.add_argument(
+ '-d',
+ '--input-directory',
+ required=True,
+ dest='input_dir',
+ help='the input directory to walk for python files to fix up',
+ )
+ parser.add_argument(
+ '-o',
+ '--output-directory',
+ required=True,
+ dest='output_dir',
+ help='the directory to output files fixed via un-flattening',
+ )
+ args = parser.parse_args()
+ input_dir = pathlib.Path(args.input_dir)
+ output_dir = pathlib.Path(args.output_dir)
+ if not input_dir.is_dir():
+ print(
+ f"input directory '{input_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if not output_dir.is_dir():
+ print(
+ f"output directory '{output_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if os.listdir(output_dir):
+ print(
+ f"output directory '{output_dir}' is not empty",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ fix_files(input_dir, output_dir)
diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py
new file mode 100644
index 00000000..d309d6e9
--- /dev/null
+++ b/scripts/readme-gen/readme_gen.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+
+# Copyright 2016 Google Inc
+#
+# 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.
+
+"""Generates READMEs using configuration defined in yaml."""
+
+import argparse
+import io
+import os
+import subprocess
+
+import jinja2
+import yaml
+
+
+jinja_env = jinja2.Environment(
+ trim_blocks=True,
+ loader=jinja2.FileSystemLoader(
+ os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates'))))
+
+README_TMPL = jinja_env.get_template('README.tmpl.rst')
+
+
+def get_help(file):
+ return subprocess.check_output(['python', file, '--help']).decode()
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('source')
+ parser.add_argument('--destination', default='README.rst')
+
+ args = parser.parse_args()
+
+ source = os.path.abspath(args.source)
+ root = os.path.dirname(source)
+ destination = os.path.join(root, args.destination)
+
+ jinja_env.globals['get_help'] = get_help
+
+ with io.open(source, 'r') as f:
+ config = yaml.load(f)
+
+ # This allows get_help to execute in the right directory.
+ os.chdir(root)
+
+ output = README_TMPL.render(config)
+
+ with io.open(destination, 'w') as f:
+ f.write(output)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/readme-gen/templates/README.tmpl.rst b/scripts/readme-gen/templates/README.tmpl.rst
new file mode 100644
index 00000000..4fd23976
--- /dev/null
+++ b/scripts/readme-gen/templates/README.tmpl.rst
@@ -0,0 +1,87 @@
+{# The following line is a lie. BUT! Once jinja2 is done with it, it will
+ become truth! #}
+.. This file is automatically generated. Do not edit this file directly.
+
+{{product.name}} Python Samples
+===============================================================================
+
+.. image:: https://gstatic.com/cloudssh/images/open-btn.png
+ :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/README.rst
+
+
+This directory contains samples for {{product.name}}. {{product.description}}
+
+{{description}}
+
+.. _{{product.name}}: {{product.url}}
+
+{% if required_api_url %}
+To run the sample, you need to enable the API at: {{required_api_url}}
+{% endif %}
+
+{% if required_role %}
+To run the sample, you need to have `{{required_role}}` role.
+{% endif %}
+
+{{other_required_steps}}
+
+{% if setup %}
+Setup
+-------------------------------------------------------------------------------
+
+{% for section in setup %}
+
+{% include section + '.tmpl.rst' %}
+
+{% endfor %}
+{% endif %}
+
+{% if samples %}
+Samples
+-------------------------------------------------------------------------------
+
+{% for sample in samples %}
+{{sample.name}}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+{% if not sample.hide_cloudshell_button %}
+.. image:: https://gstatic.com/cloudssh/images/open-btn.png
+ :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/{{sample.file}},{{folder}}/README.rst
+{% endif %}
+
+
+{{sample.description}}
+
+To run this sample:
+
+.. code-block:: bash
+
+ $ python {{sample.file}}
+{% if sample.show_help %}
+
+ {{get_help(sample.file)|indent}}
+{% endif %}
+
+
+{% endfor %}
+{% endif %}
+
+{% if cloud_client_library %}
+
+The client library
+-------------------------------------------------------------------------------
+
+This sample uses the `Google Cloud Client Library for Python`_.
+You can read the documentation for more details on API usage and use GitHub
+to `browse the source`_ and `report issues`_.
+
+.. _Google Cloud Client Library for Python:
+ https://googlecloudplatform.github.io/google-cloud-python/
+.. _browse the source:
+ https://github.com/GoogleCloudPlatform/google-cloud-python
+.. _report issues:
+ https://github.com/GoogleCloudPlatform/google-cloud-python/issues
+
+{% endif %}
+
+.. _Google Cloud SDK: https://cloud.google.com/sdk/
\ No newline at end of file
diff --git a/scripts/readme-gen/templates/auth.tmpl.rst b/scripts/readme-gen/templates/auth.tmpl.rst
new file mode 100644
index 00000000..1446b94a
--- /dev/null
+++ b/scripts/readme-gen/templates/auth.tmpl.rst
@@ -0,0 +1,9 @@
+Authentication
+++++++++++++++
+
+This sample requires you to have authentication setup. Refer to the
+`Authentication Getting Started Guide`_ for instructions on setting up
+credentials for applications.
+
+.. _Authentication Getting Started Guide:
+ https://cloud.google.com/docs/authentication/getting-started
diff --git a/scripts/readme-gen/templates/auth_api_key.tmpl.rst b/scripts/readme-gen/templates/auth_api_key.tmpl.rst
new file mode 100644
index 00000000..11957ce2
--- /dev/null
+++ b/scripts/readme-gen/templates/auth_api_key.tmpl.rst
@@ -0,0 +1,14 @@
+Authentication
+++++++++++++++
+
+Authentication for this service is done via an `API Key`_. To obtain an API
+Key:
+
+1. Open the `Cloud Platform Console`_
+2. Make sure that billing is enabled for your project.
+3. From the **Credentials** page, create a new **API Key** or use an existing
+ one for your project.
+
+.. _API Key:
+ https://developers.google.com/api-client-library/python/guide/aaa_apikeys
+.. _Cloud Console: https://console.cloud.google.com/project?_
diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst
new file mode 100644
index 00000000..a0406dba
--- /dev/null
+++ b/scripts/readme-gen/templates/install_deps.tmpl.rst
@@ -0,0 +1,29 @@
+Install Dependencies
+++++++++++++++++++++
+
+#. Clone python-docs-samples and change directory to the sample directory you want to use.
+
+ .. code-block:: bash
+
+ $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
+
+#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions.
+
+ .. _Python Development Environment Setup Guide:
+ https://cloud.google.com/python/setup
+
+#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+.
+
+ .. code-block:: bash
+
+ $ virtualenv env
+ $ source env/bin/activate
+
+#. Install the dependencies needed to run the samples.
+
+ .. code-block:: bash
+
+ $ pip install -r requirements.txt
+
+.. _pip: https://pip.pypa.io/
+.. _virtualenv: https://virtualenv.pypa.io/
diff --git a/scripts/readme-gen/templates/install_portaudio.tmpl.rst b/scripts/readme-gen/templates/install_portaudio.tmpl.rst
new file mode 100644
index 00000000..5ea33d18
--- /dev/null
+++ b/scripts/readme-gen/templates/install_portaudio.tmpl.rst
@@ -0,0 +1,35 @@
+Install PortAudio
++++++++++++++++++
+
+Install `PortAudio`_. This is required by the `PyAudio`_ library to stream
+audio from your computer's microphone. PyAudio depends on PortAudio for cross-platform compatibility, and is installed differently depending on the
+platform.
+
+* For Mac OS X, you can use `Homebrew`_::
+
+ brew install portaudio
+
+ **Note**: if you encounter an error when running `pip install` that indicates
+ it can't find `portaudio.h`, try running `pip install` with the following
+ flags::
+
+ pip install --global-option='build_ext' \
+ --global-option='-I/usr/local/include' \
+ --global-option='-L/usr/local/lib' \
+ pyaudio
+
+* For Debian / Ubuntu Linux::
+
+ apt-get install portaudio19-dev python-all-dev
+
+* Windows may work without having to install PortAudio explicitly (it will get
+ installed with PyAudio).
+
+For more details, see the `PyAudio installation`_ page.
+
+
+.. _PyAudio: https://people.csail.mit.edu/hubert/pyaudio/
+.. _PortAudio: http://www.portaudio.com/
+.. _PyAudio installation:
+ https://people.csail.mit.edu/hubert/pyaudio/#downloads
+.. _Homebrew: http://brew.sh
diff --git a/setup.py b/setup.py
index 8dac2742..9296f996 100644
--- a/setup.py
+++ b/setup.py
@@ -40,9 +40,8 @@
platforms="Posix; MacOS X; Windows",
include_package_data=True,
install_requires=(
- "google-api-core >= 1.8.0, < 2.0.0dev",
+ "google-api-core[grpc] >= 1.21.0, < 2.0.0dev",
"googleapis-common-protos >= 1.5.8",
- "grpcio >= 1.10.0",
"proto-plus >= 0.4.0",
),
python_requires=">=3.6",
diff --git a/synth.metadata b/synth.metadata
index 2064940c..f1fdff96 100644
--- a/synth.metadata
+++ b/synth.metadata
@@ -3,30 +3,30 @@
{
"git": {
"name": ".",
- "remote": "https://github.com/googleapis/python-game-servers.git",
- "sha": "1b85e6c6523fc588f235fd9e320238101c63fade"
+ "remote": "git@github.com:googleapis/python-game-servers",
+ "sha": "318bba3f5d6848f5589f67be34a0da518fffbc0c"
}
},
{
"git": {
"name": "googleapis",
"remote": "https://github.com/googleapis/googleapis.git",
- "sha": "fb21971becb6c0441efc855dabc371825732872c",
- "internalRef": "313812131"
+ "sha": "67415b43e7435d98ec104bca8cdaf4abfd3e8338",
+ "internalRef": "320987315"
}
},
{
"git": {
"name": "synthtool",
"remote": "https://github.com/googleapis/synthtool.git",
- "sha": "71b8a272549c06b5768d00fa48d3ae990e871bec"
+ "sha": "d82deccf657a66e31bd5da9efdb96c6fa322fc7e"
}
},
{
"git": {
"name": "synthtool",
"remote": "https://github.com/googleapis/synthtool.git",
- "sha": "71b8a272549c06b5768d00fa48d3ae990e871bec"
+ "sha": "d82deccf657a66e31bd5da9efdb96c6fa322fc7e"
}
}
],
diff --git a/synth.py b/synth.py
index de330a88..7d375f37 100644
--- a/synth.py
+++ b/synth.py
@@ -57,23 +57,11 @@
# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
-templated_files = common.py_library(cov_level=100)
+templated_files = common.py_library(cov_level=99, microgenerator=True)
s.move(
- templated_files, excludes=[".coveragerc"]
+ templated_files, excludes=[".coveragerc"],
) # the microgenerator has a good coveragerc file
-s.replace(
- ".gitignore", "bigquery/docs/generated", "htmlcov"
-) # temporary hack to ignore htmlcov
-# Remove 2.7 and 3.5 tests from noxfile.py
-s.replace("noxfile.py", """\["2\.7", """, "[")
-s.replace("noxfile.py", """"3.5", """, "")
-# Expand flake errors permitted to accomodate the Microgenerator
-# TODO: remove extra error codes once issues below are resolved
-# F401: https://github.com/googleapis/gapic-generator-python/issues/324
-# F821
-# F841: local variable 'client'/'response' is assigned to but never use
-s.replace(".flake8", "ignore = .*", "ignore = E203, E266, E501, W503, F401, F821, F841, W291")
s.shell.run(["nox", "-s", "blacken"], hide_output=False)
diff --git a/testing/.gitignore b/testing/.gitignore
new file mode 100644
index 00000000..b05fbd63
--- /dev/null
+++ b/testing/.gitignore
@@ -0,0 +1,3 @@
+test-env.sh
+service-account.json
+client-secrets.json
\ No newline at end of file
diff --git a/tests/unit/gaming_v1/test_game_server_clusters_service.py b/tests/unit/gaming_v1/test_game_server_clusters_service.py
deleted file mode 100644
index a1cecd09..00000000
--- a/tests/unit/gaming_v1/test_game_server_clusters_service.py
+++ /dev/null
@@ -1,985 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from unittest import mock
-
-import grpc
-import math
-import pytest
-
-from google import auth
-from google.api_core import client_options
-from google.api_core import future
-from google.api_core import grpc_helpers
-from google.api_core import operations_v1
-from google.auth import credentials
-from google.cloud.gaming_v1.services.game_server_clusters_service import (
- GameServerClustersServiceClient,
-)
-from google.cloud.gaming_v1.services.game_server_clusters_service import pagers
-from google.cloud.gaming_v1.services.game_server_clusters_service import transports
-from google.cloud.gaming_v1.types import common
-from google.cloud.gaming_v1.types import game_server_clusters
-from google.longrunning import operations_pb2
-from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
-
-def client_cert_source_callback():
- return b"cert bytes", b"key bytes"
-
-
-def test__get_default_mtls_endpoint():
- api_endpoint = "example.googleapis.com"
- api_mtls_endpoint = "example.mtls.googleapis.com"
- sandbox_endpoint = "example.sandbox.googleapis.com"
- sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
- non_googleapi = "api.example.com"
-
- assert GameServerClustersServiceClient._get_default_mtls_endpoint(None) is None
- assert (
- GameServerClustersServiceClient._get_default_mtls_endpoint(api_endpoint)
- == api_mtls_endpoint
- )
- assert (
- GameServerClustersServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
- == api_mtls_endpoint
- )
- assert (
- GameServerClustersServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- GameServerClustersServiceClient._get_default_mtls_endpoint(
- sandbox_mtls_endpoint
- )
- == sandbox_mtls_endpoint
- )
- assert (
- GameServerClustersServiceClient._get_default_mtls_endpoint(non_googleapi)
- == non_googleapi
- )
-
-
-def test_game_server_clusters_service_client_from_service_account_file():
- creds = credentials.AnonymousCredentials()
- with mock.patch.object(
- service_account.Credentials, "from_service_account_file"
- ) as factory:
- factory.return_value = creds
- client = GameServerClustersServiceClient.from_service_account_file(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- client = GameServerClustersServiceClient.from_service_account_json(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_game_server_clusters_service_client_client_options():
- # Check that if channel is provided we won't create a new one.
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_clusters_service.GameServerClustersServiceClient.get_transport_class"
- ) as gtc:
- transport = transports.GameServerClustersServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = GameServerClustersServiceClient(transport=transport)
- gtc.assert_not_called()
-
- # Check mTLS is not triggered with empty client options.
- options = client_options.ClientOptions()
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_clusters_service.GameServerClustersServiceClient.get_transport_class"
- ) as gtc:
- transport = gtc.return_value = mock.MagicMock()
- client = GameServerClustersServiceClient(client_options=options)
- transport.assert_called_once_with(
- credentials=None, host=client.DEFAULT_ENDPOINT
- )
-
- # Check mTLS is not triggered if api_endpoint is provided but
- # client_cert_source is None.
- options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_clusters_service.transports.GameServerClustersServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerClustersServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
- # Check mTLS is triggered if client_cert_source is provided.
- options = client_options.ClientOptions(
- client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_clusters_service.transports.GameServerClustersServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerClustersServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host=client.DEFAULT_ENDPOINT,
- )
-
- # Check mTLS is triggered if api_endpoint and client_cert_source are provided.
- options = client_options.ClientOptions(
- api_endpoint="squid.clam.whelk", client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_clusters_service.transports.GameServerClustersServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerClustersServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint="squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_game_server_clusters_service_client_client_options_from_dict():
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_clusters_service.transports.GameServerClustersServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerClustersServiceClient(
- client_options={"api_endpoint": "squid.clam.whelk"}
- )
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_list_game_server_clusters(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.ListGameServerClustersRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_clusters), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_clusters.ListGameServerClustersResponse(
- next_page_token="next_page_token_value", unreachable=["unreachable_value"]
- )
-
- response = client.list_game_server_clusters(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, pagers.ListGameServerClustersPager)
- assert response.next_page_token == "next_page_token_value"
- assert response.unreachable == ["unreachable_value"]
-
-
-def test_list_game_server_clusters_field_headers():
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.ListGameServerClustersRequest(parent="parent/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_clusters), "__call__"
- ) as call:
- call.return_value = game_server_clusters.ListGameServerClustersResponse()
- client.list_game_server_clusters(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"]
-
-
-def test_list_game_server_clusters_flattened():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_clusters), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_clusters.ListGameServerClustersResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.list_game_server_clusters(parent="parent_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].parent == "parent_value"
-
-
-def test_list_game_server_clusters_flattened_error():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_game_server_clusters(
- game_server_clusters.ListGameServerClustersRequest(), parent="parent_value"
- )
-
-
-def test_list_game_server_clusters_pager():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_clusters), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[
- game_server_clusters.GameServerCluster(),
- game_server_clusters.GameServerCluster(),
- game_server_clusters.GameServerCluster(),
- ],
- next_page_token="abc",
- ),
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[], next_page_token="def"
- ),
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[game_server_clusters.GameServerCluster()],
- next_page_token="ghi",
- ),
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[
- game_server_clusters.GameServerCluster(),
- game_server_clusters.GameServerCluster(),
- ]
- ),
- RuntimeError,
- )
- results = [i for i in client.list_game_server_clusters(request={})]
- assert len(results) == 6
- assert all(
- isinstance(i, game_server_clusters.GameServerCluster) for i in results
- )
-
-
-def test_list_game_server_clusters_pages():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_clusters), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[
- game_server_clusters.GameServerCluster(),
- game_server_clusters.GameServerCluster(),
- game_server_clusters.GameServerCluster(),
- ],
- next_page_token="abc",
- ),
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[], next_page_token="def"
- ),
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[game_server_clusters.GameServerCluster()],
- next_page_token="ghi",
- ),
- game_server_clusters.ListGameServerClustersResponse(
- game_server_clusters=[
- game_server_clusters.GameServerCluster(),
- game_server_clusters.GameServerCluster(),
- ]
- ),
- RuntimeError,
- )
- pages = list(client.list_game_server_clusters(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_get_game_server_cluster(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.GetGameServerClusterRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_clusters.GameServerCluster(
- name="name_value", etag="etag_value", description="description_value"
- )
-
- response = client.get_game_server_cluster(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, game_server_clusters.GameServerCluster)
- assert response.name == "name_value"
- assert response.etag == "etag_value"
- assert response.description == "description_value"
-
-
-def test_get_game_server_cluster_field_headers():
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.GetGameServerClusterRequest(name="name/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_cluster), "__call__"
- ) as call:
- call.return_value = game_server_clusters.GameServerCluster()
- client.get_game_server_cluster(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"]
-
-
-def test_get_game_server_cluster_flattened():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_clusters.GameServerCluster()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_game_server_cluster(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_get_game_server_cluster_flattened_error():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_game_server_cluster(
- game_server_clusters.GetGameServerClusterRequest(), name="name_value"
- )
-
-
-def test_create_game_server_cluster(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.CreateGameServerClusterRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.create_game_server_cluster(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, future.Future)
-
-
-def test_create_game_server_cluster_flattened():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_game_server_cluster), "__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.
- response = client.create_game_server_cluster(
- parent="parent_value",
- game_server_cluster=game_server_clusters.GameServerCluster(
- name="name_value"
- ),
- game_server_cluster_id="game_server_cluster_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]
- assert args[0].parent == "parent_value"
- assert args[0].game_server_cluster == game_server_clusters.GameServerCluster(
- name="name_value"
- )
- assert args[0].game_server_cluster_id == "game_server_cluster_id_value"
-
-
-def test_create_game_server_cluster_flattened_error():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_game_server_cluster(
- game_server_clusters.CreateGameServerClusterRequest(),
- parent="parent_value",
- game_server_cluster=game_server_clusters.GameServerCluster(
- name="name_value"
- ),
- game_server_cluster_id="game_server_cluster_id_value",
- )
-
-
-def test_preview_create_game_server_cluster(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.PreviewCreateGameServerClusterRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.preview_create_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_clusters.PreviewCreateGameServerClusterResponse(
- etag="etag_value"
- )
-
- response = client.preview_create_game_server_cluster(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, game_server_clusters.PreviewCreateGameServerClusterResponse
- )
- assert response.etag == "etag_value"
-
-
-def test_delete_game_server_cluster(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.DeleteGameServerClusterRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.delete_game_server_cluster(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, future.Future)
-
-
-def test_delete_game_server_cluster_flattened():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_game_server_cluster), "__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.
- response = client.delete_game_server_cluster(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_delete_game_server_cluster_flattened_error():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_game_server_cluster(
- game_server_clusters.DeleteGameServerClusterRequest(), name="name_value"
- )
-
-
-def test_preview_delete_game_server_cluster(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.PreviewDeleteGameServerClusterRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.preview_delete_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_clusters.PreviewDeleteGameServerClusterResponse(
- etag="etag_value"
- )
-
- response = client.preview_delete_game_server_cluster(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, game_server_clusters.PreviewDeleteGameServerClusterResponse
- )
- assert response.etag == "etag_value"
-
-
-def test_update_game_server_cluster(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.UpdateGameServerClusterRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.update_game_server_cluster(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, future.Future)
-
-
-def test_update_game_server_cluster_flattened():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_game_server_cluster), "__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.
- response = client.update_game_server_cluster(
- game_server_cluster=game_server_clusters.GameServerCluster(
- name="name_value"
- ),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].game_server_cluster == game_server_clusters.GameServerCluster(
- name="name_value"
- )
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
-
-
-def test_update_game_server_cluster_flattened_error():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_game_server_cluster(
- game_server_clusters.UpdateGameServerClusterRequest(),
- game_server_cluster=game_server_clusters.GameServerCluster(
- name="name_value"
- ),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_preview_update_game_server_cluster(transport: str = "grpc"):
- client = GameServerClustersServiceClient(
- credentials=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 = game_server_clusters.PreviewUpdateGameServerClusterRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.preview_update_game_server_cluster), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_clusters.PreviewUpdateGameServerClusterResponse(
- etag="etag_value"
- )
-
- response = client.preview_update_game_server_cluster(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, game_server_clusters.PreviewUpdateGameServerClusterResponse
- )
- assert response.etag == "etag_value"
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.GameServerClustersServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- with pytest.raises(ValueError):
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.GameServerClustersServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = GameServerClustersServiceClient(transport=transport)
- assert client._transport is transport
-
-
-def test_transport_grpc_default():
- # A client should use the gRPC transport by default.
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
- assert isinstance(
- client._transport, transports.GameServerClustersServiceGrpcTransport
- )
-
-
-def test_game_server_clusters_service_base_transport():
- # Instantiate the base transport.
- transport = transports.GameServerClustersServiceTransport(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Every method on the transport should just blindly
- # raise NotImplementedError.
- methods = (
- "list_game_server_clusters",
- "get_game_server_cluster",
- "create_game_server_cluster",
- "preview_create_game_server_cluster",
- "delete_game_server_cluster",
- "preview_delete_game_server_cluster",
- "update_game_server_cluster",
- "preview_update_game_server_cluster",
- )
- for method in methods:
- with pytest.raises(NotImplementedError):
- getattr(transport, method)(request=object())
-
- # Additionally, the LRO client (a property) should
- # also raise NotImplementedError
- with pytest.raises(NotImplementedError):
- transport.operations_client
-
-
-def test_game_server_clusters_service_auth_adc():
- # If no credentials are provided, we should use ADC credentials.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
- GameServerClustersServiceClient()
- adc.assert_called_once_with(
- scopes=("https://www.googleapis.com/auth/cloud-platform",)
- )
-
-
-def test_game_server_clusters_service_host_no_port():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_game_server_clusters_service_host_with_port():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com:8000"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:8000"
-
-
-def test_game_server_clusters_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
-
- # Check that if channel is provided, mtls endpoint and client_cert_source
- # won't be used.
- callback = mock.MagicMock()
- transport = transports.GameServerClustersServiceGrpcTransport(
- host="squid.clam.whelk",
- channel=channel,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=callback,
- )
- assert transport.grpc_channel == channel
- assert transport._host == "squid.clam.whelk:443"
- assert not callback.called
-
-
-@mock.patch("grpc.ssl_channel_credentials", autospec=True)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_game_server_clusters_service_grpc_transport_channel_mtls_with_client_cert_source(
- grpc_create_channel, grpc_ssl_channel_cred
-):
- # Check that if channel is None, but api_mtls_endpoint and client_cert_source
- # are provided, then a mTLS channel will be created.
- mock_cred = mock.Mock()
-
- mock_ssl_cred = mock.Mock()
- grpc_ssl_channel_cred.return_value = mock_ssl_cred
-
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- transport = transports.GameServerClustersServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- )
- grpc_ssl_channel_cred.assert_called_once_with(
- certificate_chain=b"cert bytes", private_key=b"key bytes"
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-@pytest.mark.parametrize(
- "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
-)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_game_server_clusters_service_grpc_transport_channel_mtls_with_adc(
- grpc_create_channel, api_mtls_endpoint
-):
- # Check that if channel and client_cert_source are None, but api_mtls_endpoint
- # is provided, then a mTLS channel will be created with SSL ADC.
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- # Mock google.auth.transport.grpc.SslCredentials class.
- mock_ssl_cred = mock.Mock()
- with mock.patch.multiple(
- "google.auth.transport.grpc.SslCredentials",
- __init__=mock.Mock(return_value=None),
- ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
- ):
- mock_cred = mock.Mock()
- transport = transports.GameServerClustersServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint=api_mtls_endpoint,
- client_cert_source=None,
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-def test_game_server_clusters_service_grpc_lro_client():
- client = GameServerClustersServiceClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc"
- )
- transport = client._transport
-
- # Ensure that we have a api-core operations client.
- assert isinstance(transport.operations_client, operations_v1.OperationsClient)
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
-
-
-def test_game_server_cluster_path():
- project = "squid"
- location = "clam"
- realm = "whelk"
- cluster = "octopus"
-
- expected = "projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}".format(
- project=project, location=location, realm=realm, cluster=cluster
- )
- actual = GameServerClustersServiceClient.game_server_cluster_path(
- project, location, realm, cluster
- )
- assert expected == actual
-
-
-def test_parse_game_server_cluster_path():
- expected = {
- "project": "oyster",
- "location": "nudibranch",
- "realm": "cuttlefish",
- "cluster": "mussel",
- }
- path = GameServerClustersServiceClient.game_server_cluster_path(**expected)
-
- # Check that the path construction is reversible.
- actual = GameServerClustersServiceClient.parse_game_server_cluster_path(path)
- assert expected == actual
diff --git a/tests/unit/gaming_v1/test_game_server_configs_service.py b/tests/unit/gaming_v1/test_game_server_configs_service.py
deleted file mode 100644
index 0561baf4..00000000
--- a/tests/unit/gaming_v1/test_game_server_configs_service.py
+++ /dev/null
@@ -1,794 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from unittest import mock
-
-import grpc
-import math
-import pytest
-
-from google import auth
-from google.api_core import client_options
-from google.api_core import future
-from google.api_core import grpc_helpers
-from google.api_core import operations_v1
-from google.auth import credentials
-from google.cloud.gaming_v1.services.game_server_configs_service import (
- GameServerConfigsServiceClient,
-)
-from google.cloud.gaming_v1.services.game_server_configs_service import pagers
-from google.cloud.gaming_v1.services.game_server_configs_service import transports
-from google.cloud.gaming_v1.types import common
-from google.cloud.gaming_v1.types import game_server_configs
-from google.longrunning import operations_pb2
-from google.oauth2 import service_account
-from google.protobuf import duration_pb2 as duration # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
-
-def client_cert_source_callback():
- return b"cert bytes", b"key bytes"
-
-
-def test__get_default_mtls_endpoint():
- api_endpoint = "example.googleapis.com"
- api_mtls_endpoint = "example.mtls.googleapis.com"
- sandbox_endpoint = "example.sandbox.googleapis.com"
- sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
- non_googleapi = "api.example.com"
-
- assert GameServerConfigsServiceClient._get_default_mtls_endpoint(None) is None
- assert (
- GameServerConfigsServiceClient._get_default_mtls_endpoint(api_endpoint)
- == api_mtls_endpoint
- )
- assert (
- GameServerConfigsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
- == api_mtls_endpoint
- )
- assert (
- GameServerConfigsServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- GameServerConfigsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- GameServerConfigsServiceClient._get_default_mtls_endpoint(non_googleapi)
- == non_googleapi
- )
-
-
-def test_game_server_configs_service_client_from_service_account_file():
- creds = credentials.AnonymousCredentials()
- with mock.patch.object(
- service_account.Credentials, "from_service_account_file"
- ) as factory:
- factory.return_value = creds
- client = GameServerConfigsServiceClient.from_service_account_file(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- client = GameServerConfigsServiceClient.from_service_account_json(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_game_server_configs_service_client_client_options():
- # Check that if channel is provided we won't create a new one.
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_configs_service.GameServerConfigsServiceClient.get_transport_class"
- ) as gtc:
- transport = transports.GameServerConfigsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = GameServerConfigsServiceClient(transport=transport)
- gtc.assert_not_called()
-
- # Check mTLS is not triggered with empty client options.
- options = client_options.ClientOptions()
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_configs_service.GameServerConfigsServiceClient.get_transport_class"
- ) as gtc:
- transport = gtc.return_value = mock.MagicMock()
- client = GameServerConfigsServiceClient(client_options=options)
- transport.assert_called_once_with(
- credentials=None, host=client.DEFAULT_ENDPOINT
- )
-
- # Check mTLS is not triggered if api_endpoint is provided but
- # client_cert_source is None.
- options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_configs_service.transports.GameServerConfigsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerConfigsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
- # Check mTLS is triggered if client_cert_source is provided.
- options = client_options.ClientOptions(
- client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_configs_service.transports.GameServerConfigsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerConfigsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host=client.DEFAULT_ENDPOINT,
- )
-
- # Check mTLS is triggered if api_endpoint and client_cert_source are provided.
- options = client_options.ClientOptions(
- api_endpoint="squid.clam.whelk", client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_configs_service.transports.GameServerConfigsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerConfigsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint="squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_game_server_configs_service_client_client_options_from_dict():
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_configs_service.transports.GameServerConfigsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerConfigsServiceClient(
- client_options={"api_endpoint": "squid.clam.whelk"}
- )
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_list_game_server_configs(transport: str = "grpc"):
- client = GameServerConfigsServiceClient(
- credentials=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 = game_server_configs.ListGameServerConfigsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_configs), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_configs.ListGameServerConfigsResponse(
- next_page_token="next_page_token_value", unreachable=["unreachable_value"]
- )
-
- response = client.list_game_server_configs(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, pagers.ListGameServerConfigsPager)
- assert response.next_page_token == "next_page_token_value"
- assert response.unreachable == ["unreachable_value"]
-
-
-def test_list_game_server_configs_field_headers():
- client = GameServerConfigsServiceClient(
- credentials=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 = game_server_configs.ListGameServerConfigsRequest(parent="parent/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_configs), "__call__"
- ) as call:
- call.return_value = game_server_configs.ListGameServerConfigsResponse()
- client.list_game_server_configs(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"]
-
-
-def test_list_game_server_configs_flattened():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_configs), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_configs.ListGameServerConfigsResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.list_game_server_configs(parent="parent_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].parent == "parent_value"
-
-
-def test_list_game_server_configs_flattened_error():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_game_server_configs(
- game_server_configs.ListGameServerConfigsRequest(), parent="parent_value"
- )
-
-
-def test_list_game_server_configs_pager():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_configs), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[
- game_server_configs.GameServerConfig(),
- game_server_configs.GameServerConfig(),
- game_server_configs.GameServerConfig(),
- ],
- next_page_token="abc",
- ),
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[], next_page_token="def"
- ),
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[game_server_configs.GameServerConfig()],
- next_page_token="ghi",
- ),
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[
- game_server_configs.GameServerConfig(),
- game_server_configs.GameServerConfig(),
- ]
- ),
- RuntimeError,
- )
- results = [i for i in client.list_game_server_configs(request={})]
- assert len(results) == 6
- assert all(isinstance(i, game_server_configs.GameServerConfig) for i in results)
-
-
-def test_list_game_server_configs_pages():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_configs), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[
- game_server_configs.GameServerConfig(),
- game_server_configs.GameServerConfig(),
- game_server_configs.GameServerConfig(),
- ],
- next_page_token="abc",
- ),
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[], next_page_token="def"
- ),
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[game_server_configs.GameServerConfig()],
- next_page_token="ghi",
- ),
- game_server_configs.ListGameServerConfigsResponse(
- game_server_configs=[
- game_server_configs.GameServerConfig(),
- game_server_configs.GameServerConfig(),
- ]
- ),
- RuntimeError,
- )
- pages = list(client.list_game_server_configs(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_get_game_server_config(transport: str = "grpc"):
- client = GameServerConfigsServiceClient(
- credentials=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 = game_server_configs.GetGameServerConfigRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_config), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_configs.GameServerConfig(
- name="name_value", description="description_value"
- )
-
- response = client.get_game_server_config(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, game_server_configs.GameServerConfig)
- assert response.name == "name_value"
- assert response.description == "description_value"
-
-
-def test_get_game_server_config_field_headers():
- client = GameServerConfigsServiceClient(
- credentials=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 = game_server_configs.GetGameServerConfigRequest(name="name/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_config), "__call__"
- ) as call:
- call.return_value = game_server_configs.GameServerConfig()
- client.get_game_server_config(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"]
-
-
-def test_get_game_server_config_flattened():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_config), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_configs.GameServerConfig()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_game_server_config(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_get_game_server_config_flattened_error():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_game_server_config(
- game_server_configs.GetGameServerConfigRequest(), name="name_value"
- )
-
-
-def test_create_game_server_config(transport: str = "grpc"):
- client = GameServerConfigsServiceClient(
- credentials=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 = game_server_configs.CreateGameServerConfigRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_game_server_config), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.create_game_server_config(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, future.Future)
-
-
-def test_create_game_server_config_flattened():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_game_server_config), "__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.
- response = client.create_game_server_config(
- parent="parent_value",
- game_server_config=game_server_configs.GameServerConfig(name="name_value"),
- )
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].parent == "parent_value"
- assert args[0].game_server_config == game_server_configs.GameServerConfig(
- name="name_value"
- )
-
-
-def test_create_game_server_config_flattened_error():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_game_server_config(
- game_server_configs.CreateGameServerConfigRequest(),
- parent="parent_value",
- game_server_config=game_server_configs.GameServerConfig(name="name_value"),
- )
-
-
-def test_delete_game_server_config(transport: str = "grpc"):
- client = GameServerConfigsServiceClient(
- credentials=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 = game_server_configs.DeleteGameServerConfigRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_game_server_config), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.delete_game_server_config(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, future.Future)
-
-
-def test_delete_game_server_config_flattened():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_game_server_config), "__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.
- response = client.delete_game_server_config(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_delete_game_server_config_flattened_error():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_game_server_config(
- game_server_configs.DeleteGameServerConfigRequest(), name="name_value"
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.GameServerConfigsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- with pytest.raises(ValueError):
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.GameServerConfigsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = GameServerConfigsServiceClient(transport=transport)
- assert client._transport is transport
-
-
-def test_transport_grpc_default():
- # A client should use the gRPC transport by default.
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
- assert isinstance(
- client._transport, transports.GameServerConfigsServiceGrpcTransport
- )
-
-
-def test_game_server_configs_service_base_transport():
- # Instantiate the base transport.
- transport = transports.GameServerConfigsServiceTransport(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Every method on the transport should just blindly
- # raise NotImplementedError.
- methods = (
- "list_game_server_configs",
- "get_game_server_config",
- "create_game_server_config",
- "delete_game_server_config",
- )
- for method in methods:
- with pytest.raises(NotImplementedError):
- getattr(transport, method)(request=object())
-
- # Additionally, the LRO client (a property) should
- # also raise NotImplementedError
- with pytest.raises(NotImplementedError):
- transport.operations_client
-
-
-def test_game_server_configs_service_auth_adc():
- # If no credentials are provided, we should use ADC credentials.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
- GameServerConfigsServiceClient()
- adc.assert_called_once_with(
- scopes=("https://www.googleapis.com/auth/cloud-platform",)
- )
-
-
-def test_game_server_configs_service_host_no_port():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_game_server_configs_service_host_with_port():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com:8000"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:8000"
-
-
-def test_game_server_configs_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
-
- # Check that if channel is provided, mtls endpoint and client_cert_source
- # won't be used.
- callback = mock.MagicMock()
- transport = transports.GameServerConfigsServiceGrpcTransport(
- host="squid.clam.whelk",
- channel=channel,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=callback,
- )
- assert transport.grpc_channel == channel
- assert transport._host == "squid.clam.whelk:443"
- assert not callback.called
-
-
-@mock.patch("grpc.ssl_channel_credentials", autospec=True)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_game_server_configs_service_grpc_transport_channel_mtls_with_client_cert_source(
- grpc_create_channel, grpc_ssl_channel_cred
-):
- # Check that if channel is None, but api_mtls_endpoint and client_cert_source
- # are provided, then a mTLS channel will be created.
- mock_cred = mock.Mock()
-
- mock_ssl_cred = mock.Mock()
- grpc_ssl_channel_cred.return_value = mock_ssl_cred
-
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- transport = transports.GameServerConfigsServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- )
- grpc_ssl_channel_cred.assert_called_once_with(
- certificate_chain=b"cert bytes", private_key=b"key bytes"
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-@pytest.mark.parametrize(
- "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
-)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_game_server_configs_service_grpc_transport_channel_mtls_with_adc(
- grpc_create_channel, api_mtls_endpoint
-):
- # Check that if channel and client_cert_source are None, but api_mtls_endpoint
- # is provided, then a mTLS channel will be created with SSL ADC.
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- # Mock google.auth.transport.grpc.SslCredentials class.
- mock_ssl_cred = mock.Mock()
- with mock.patch.multiple(
- "google.auth.transport.grpc.SslCredentials",
- __init__=mock.Mock(return_value=None),
- ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
- ):
- mock_cred = mock.Mock()
- transport = transports.GameServerConfigsServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint=api_mtls_endpoint,
- client_cert_source=None,
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-def test_game_server_configs_service_grpc_lro_client():
- client = GameServerConfigsServiceClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc"
- )
- transport = client._transport
-
- # Ensure that we have a api-core operations client.
- assert isinstance(transport.operations_client, operations_v1.OperationsClient)
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
-
-
-def test_game_server_config_path():
- project = "squid"
- location = "clam"
- deployment = "whelk"
- config = "octopus"
-
- expected = "projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}".format(
- project=project, location=location, deployment=deployment, config=config
- )
- actual = GameServerConfigsServiceClient.game_server_config_path(
- project, location, deployment, config
- )
- assert expected == actual
-
-
-def test_parse_game_server_config_path():
- expected = {
- "project": "oyster",
- "location": "nudibranch",
- "deployment": "cuttlefish",
- "config": "mussel",
- }
- path = GameServerConfigsServiceClient.game_server_config_path(**expected)
-
- # Check that the path construction is reversible.
- actual = GameServerConfigsServiceClient.parse_game_server_config_path(path)
- assert expected == actual
diff --git a/tests/unit/gaming_v1/test_game_server_deployments_service.py b/tests/unit/gaming_v1/test_game_server_deployments_service.py
deleted file mode 100644
index 847eb83f..00000000
--- a/tests/unit/gaming_v1/test_game_server_deployments_service.py
+++ /dev/null
@@ -1,1158 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from unittest import mock
-
-import grpc
-import math
-import pytest
-
-from google import auth
-from google.api_core import client_options
-from google.api_core import future
-from google.api_core import grpc_helpers
-from google.api_core import operations_v1
-from google.auth import credentials
-from google.cloud.gaming_v1.services.game_server_deployments_service import (
- GameServerDeploymentsServiceClient,
-)
-from google.cloud.gaming_v1.services.game_server_deployments_service import pagers
-from google.cloud.gaming_v1.services.game_server_deployments_service import transports
-from google.cloud.gaming_v1.types import common
-from google.cloud.gaming_v1.types import game_server_deployments
-from google.longrunning import operations_pb2
-from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
-
-def client_cert_source_callback():
- return b"cert bytes", b"key bytes"
-
-
-def test__get_default_mtls_endpoint():
- api_endpoint = "example.googleapis.com"
- api_mtls_endpoint = "example.mtls.googleapis.com"
- sandbox_endpoint = "example.sandbox.googleapis.com"
- sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
- non_googleapi = "api.example.com"
-
- assert GameServerDeploymentsServiceClient._get_default_mtls_endpoint(None) is None
- assert (
- GameServerDeploymentsServiceClient._get_default_mtls_endpoint(api_endpoint)
- == api_mtls_endpoint
- )
- assert (
- GameServerDeploymentsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
- == api_mtls_endpoint
- )
- assert (
- GameServerDeploymentsServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- GameServerDeploymentsServiceClient._get_default_mtls_endpoint(
- sandbox_mtls_endpoint
- )
- == sandbox_mtls_endpoint
- )
- assert (
- GameServerDeploymentsServiceClient._get_default_mtls_endpoint(non_googleapi)
- == non_googleapi
- )
-
-
-def test_game_server_deployments_service_client_from_service_account_file():
- creds = credentials.AnonymousCredentials()
- with mock.patch.object(
- service_account.Credentials, "from_service_account_file"
- ) as factory:
- factory.return_value = creds
- client = GameServerDeploymentsServiceClient.from_service_account_file(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- client = GameServerDeploymentsServiceClient.from_service_account_json(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_game_server_deployments_service_client_client_options():
- # Check that if channel is provided we won't create a new one.
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_deployments_service.GameServerDeploymentsServiceClient.get_transport_class"
- ) as gtc:
- transport = transports.GameServerDeploymentsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = GameServerDeploymentsServiceClient(transport=transport)
- gtc.assert_not_called()
-
- # Check mTLS is not triggered with empty client options.
- options = client_options.ClientOptions()
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_deployments_service.GameServerDeploymentsServiceClient.get_transport_class"
- ) as gtc:
- transport = gtc.return_value = mock.MagicMock()
- client = GameServerDeploymentsServiceClient(client_options=options)
- transport.assert_called_once_with(
- credentials=None, host=client.DEFAULT_ENDPOINT
- )
-
- # Check mTLS is not triggered if api_endpoint is provided but
- # client_cert_source is None.
- options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerDeploymentsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
- # Check mTLS is triggered if client_cert_source is provided.
- options = client_options.ClientOptions(
- client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerDeploymentsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host=client.DEFAULT_ENDPOINT,
- )
-
- # Check mTLS is triggered if api_endpoint and client_cert_source are provided.
- options = client_options.ClientOptions(
- api_endpoint="squid.clam.whelk", client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerDeploymentsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint="squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_game_server_deployments_service_client_client_options_from_dict():
- with mock.patch(
- "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = GameServerDeploymentsServiceClient(
- client_options={"api_endpoint": "squid.clam.whelk"}
- )
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_list_game_server_deployments(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.ListGameServerDeploymentsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_deployments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.ListGameServerDeploymentsResponse(
- next_page_token="next_page_token_value", unreachable=["unreachable_value"]
- )
-
- response = client.list_game_server_deployments(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, pagers.ListGameServerDeploymentsPager)
- assert response.next_page_token == "next_page_token_value"
- assert response.unreachable == ["unreachable_value"]
-
-
-def test_list_game_server_deployments_field_headers():
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.ListGameServerDeploymentsRequest(
- parent="parent/value"
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_deployments), "__call__"
- ) as call:
- call.return_value = game_server_deployments.ListGameServerDeploymentsResponse()
- client.list_game_server_deployments(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"]
-
-
-def test_list_game_server_deployments_flattened():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_deployments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.ListGameServerDeploymentsResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.list_game_server_deployments(parent="parent_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].parent == "parent_value"
-
-
-def test_list_game_server_deployments_flattened_error():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_game_server_deployments(
- game_server_deployments.ListGameServerDeploymentsRequest(),
- parent="parent_value",
- )
-
-
-def test_list_game_server_deployments_pager():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_deployments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[
- game_server_deployments.GameServerDeployment(),
- game_server_deployments.GameServerDeployment(),
- game_server_deployments.GameServerDeployment(),
- ],
- next_page_token="abc",
- ),
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[], next_page_token="def"
- ),
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[
- game_server_deployments.GameServerDeployment()
- ],
- next_page_token="ghi",
- ),
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[
- game_server_deployments.GameServerDeployment(),
- game_server_deployments.GameServerDeployment(),
- ]
- ),
- RuntimeError,
- )
- results = [i for i in client.list_game_server_deployments(request={})]
- assert len(results) == 6
- assert all(
- isinstance(i, game_server_deployments.GameServerDeployment) for i in results
- )
-
-
-def test_list_game_server_deployments_pages():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_game_server_deployments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[
- game_server_deployments.GameServerDeployment(),
- game_server_deployments.GameServerDeployment(),
- game_server_deployments.GameServerDeployment(),
- ],
- next_page_token="abc",
- ),
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[], next_page_token="def"
- ),
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[
- game_server_deployments.GameServerDeployment()
- ],
- next_page_token="ghi",
- ),
- game_server_deployments.ListGameServerDeploymentsResponse(
- game_server_deployments=[
- game_server_deployments.GameServerDeployment(),
- game_server_deployments.GameServerDeployment(),
- ]
- ),
- RuntimeError,
- )
- pages = list(client.list_game_server_deployments(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_get_game_server_deployment(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.GetGameServerDeploymentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_deployment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.GameServerDeployment(
- name="name_value", etag="etag_value", description="description_value"
- )
-
- response = client.get_game_server_deployment(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, game_server_deployments.GameServerDeployment)
- assert response.name == "name_value"
- assert response.etag == "etag_value"
- assert response.description == "description_value"
-
-
-def test_get_game_server_deployment_field_headers():
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.GetGameServerDeploymentRequest(name="name/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_deployment), "__call__"
- ) as call:
- call.return_value = game_server_deployments.GameServerDeployment()
- client.get_game_server_deployment(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"]
-
-
-def test_get_game_server_deployment_flattened():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_deployment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.GameServerDeployment()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_game_server_deployment(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_get_game_server_deployment_flattened_error():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_game_server_deployment(
- game_server_deployments.GetGameServerDeploymentRequest(), name="name_value"
- )
-
-
-def test_create_game_server_deployment(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.CreateGameServerDeploymentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_game_server_deployment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.create_game_server_deployment(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, future.Future)
-
-
-def test_create_game_server_deployment_flattened():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_game_server_deployment), "__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.
- response = client.create_game_server_deployment(
- parent="parent_value",
- game_server_deployment=game_server_deployments.GameServerDeployment(
- name="name_value"
- ),
- )
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].parent == "parent_value"
- assert args[
- 0
- ].game_server_deployment == game_server_deployments.GameServerDeployment(
- name="name_value"
- )
-
-
-def test_create_game_server_deployment_flattened_error():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_game_server_deployment(
- game_server_deployments.CreateGameServerDeploymentRequest(),
- parent="parent_value",
- game_server_deployment=game_server_deployments.GameServerDeployment(
- name="name_value"
- ),
- )
-
-
-def test_delete_game_server_deployment(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.DeleteGameServerDeploymentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_game_server_deployment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.delete_game_server_deployment(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, future.Future)
-
-
-def test_delete_game_server_deployment_flattened():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_game_server_deployment), "__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.
- response = client.delete_game_server_deployment(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_delete_game_server_deployment_flattened_error():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_game_server_deployment(
- game_server_deployments.DeleteGameServerDeploymentRequest(),
- name="name_value",
- )
-
-
-def test_update_game_server_deployment(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.UpdateGameServerDeploymentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_game_server_deployment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.update_game_server_deployment(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, future.Future)
-
-
-def test_update_game_server_deployment_flattened():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_game_server_deployment), "__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.
- response = client.update_game_server_deployment(
- game_server_deployment=game_server_deployments.GameServerDeployment(
- name="name_value"
- ),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[
- 0
- ].game_server_deployment == game_server_deployments.GameServerDeployment(
- name="name_value"
- )
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
-
-
-def test_update_game_server_deployment_flattened_error():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_game_server_deployment(
- game_server_deployments.UpdateGameServerDeploymentRequest(),
- game_server_deployment=game_server_deployments.GameServerDeployment(
- name="name_value"
- ),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_get_game_server_deployment_rollout(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.GetGameServerDeploymentRolloutRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_deployment_rollout), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.GameServerDeploymentRollout(
- name="name_value",
- default_game_server_config="default_game_server_config_value",
- etag="etag_value",
- )
-
- response = client.get_game_server_deployment_rollout(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, game_server_deployments.GameServerDeploymentRollout)
- assert response.name == "name_value"
- assert response.default_game_server_config == "default_game_server_config_value"
- assert response.etag == "etag_value"
-
-
-def test_get_game_server_deployment_rollout_field_headers():
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.GetGameServerDeploymentRolloutRequest(
- name="name/value"
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_deployment_rollout), "__call__"
- ) as call:
- call.return_value = game_server_deployments.GameServerDeploymentRollout()
- client.get_game_server_deployment_rollout(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"]
-
-
-def test_get_game_server_deployment_rollout_flattened():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_game_server_deployment_rollout), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.GameServerDeploymentRollout()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_game_server_deployment_rollout(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_get_game_server_deployment_rollout_flattened_error():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_game_server_deployment_rollout(
- game_server_deployments.GetGameServerDeploymentRolloutRequest(),
- name="name_value",
- )
-
-
-def test_update_game_server_deployment_rollout(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.UpdateGameServerDeploymentRolloutRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_game_server_deployment_rollout), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.update_game_server_deployment_rollout(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, future.Future)
-
-
-def test_update_game_server_deployment_rollout_flattened():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_game_server_deployment_rollout), "__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.
- response = client.update_game_server_deployment_rollout(
- rollout=game_server_deployments.GameServerDeploymentRollout(
- name="name_value"
- ),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].rollout == game_server_deployments.GameServerDeploymentRollout(
- name="name_value"
- )
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
-
-
-def test_update_game_server_deployment_rollout_flattened_error():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_game_server_deployment_rollout(
- game_server_deployments.UpdateGameServerDeploymentRolloutRequest(),
- rollout=game_server_deployments.GameServerDeploymentRollout(
- name="name_value"
- ),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_preview_game_server_deployment_rollout(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.PreviewGameServerDeploymentRolloutRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.preview_game_server_deployment_rollout), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.PreviewGameServerDeploymentRolloutResponse(
- unavailable=["unavailable_value"], etag="etag_value"
- )
-
- response = client.preview_game_server_deployment_rollout(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, game_server_deployments.PreviewGameServerDeploymentRolloutResponse
- )
- assert response.unavailable == ["unavailable_value"]
- assert response.etag == "etag_value"
-
-
-def test_fetch_deployment_state(transport: str = "grpc"):
- client = GameServerDeploymentsServiceClient(
- credentials=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 = game_server_deployments.FetchDeploymentStateRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.fetch_deployment_state), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = game_server_deployments.FetchDeploymentStateResponse(
- unavailable=["unavailable_value"]
- )
-
- response = client.fetch_deployment_state(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, game_server_deployments.FetchDeploymentStateResponse)
- assert response.unavailable == ["unavailable_value"]
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.GameServerDeploymentsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- with pytest.raises(ValueError):
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.GameServerDeploymentsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = GameServerDeploymentsServiceClient(transport=transport)
- assert client._transport is transport
-
-
-def test_transport_grpc_default():
- # A client should use the gRPC transport by default.
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials()
- )
- assert isinstance(
- client._transport, transports.GameServerDeploymentsServiceGrpcTransport
- )
-
-
-def test_game_server_deployments_service_base_transport():
- # Instantiate the base transport.
- transport = transports.GameServerDeploymentsServiceTransport(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Every method on the transport should just blindly
- # raise NotImplementedError.
- methods = (
- "list_game_server_deployments",
- "get_game_server_deployment",
- "create_game_server_deployment",
- "delete_game_server_deployment",
- "update_game_server_deployment",
- "get_game_server_deployment_rollout",
- "update_game_server_deployment_rollout",
- "preview_game_server_deployment_rollout",
- "fetch_deployment_state",
- )
- for method in methods:
- with pytest.raises(NotImplementedError):
- getattr(transport, method)(request=object())
-
- # Additionally, the LRO client (a property) should
- # also raise NotImplementedError
- with pytest.raises(NotImplementedError):
- transport.operations_client
-
-
-def test_game_server_deployments_service_auth_adc():
- # If no credentials are provided, we should use ADC credentials.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
- GameServerDeploymentsServiceClient()
- adc.assert_called_once_with(
- scopes=("https://www.googleapis.com/auth/cloud-platform",)
- )
-
-
-def test_game_server_deployments_service_host_no_port():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_game_server_deployments_service_host_with_port():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com:8000"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:8000"
-
-
-def test_game_server_deployments_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
-
- # Check that if channel is provided, mtls endpoint and client_cert_source
- # won't be used.
- callback = mock.MagicMock()
- transport = transports.GameServerDeploymentsServiceGrpcTransport(
- host="squid.clam.whelk",
- channel=channel,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=callback,
- )
- assert transport.grpc_channel == channel
- assert transport._host == "squid.clam.whelk:443"
- assert not callback.called
-
-
-@mock.patch("grpc.ssl_channel_credentials", autospec=True)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_game_server_deployments_service_grpc_transport_channel_mtls_with_client_cert_source(
- grpc_create_channel, grpc_ssl_channel_cred
-):
- # Check that if channel is None, but api_mtls_endpoint and client_cert_source
- # are provided, then a mTLS channel will be created.
- mock_cred = mock.Mock()
-
- mock_ssl_cred = mock.Mock()
- grpc_ssl_channel_cred.return_value = mock_ssl_cred
-
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- transport = transports.GameServerDeploymentsServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- )
- grpc_ssl_channel_cred.assert_called_once_with(
- certificate_chain=b"cert bytes", private_key=b"key bytes"
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-@pytest.mark.parametrize(
- "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
-)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_game_server_deployments_service_grpc_transport_channel_mtls_with_adc(
- grpc_create_channel, api_mtls_endpoint
-):
- # Check that if channel and client_cert_source are None, but api_mtls_endpoint
- # is provided, then a mTLS channel will be created with SSL ADC.
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- # Mock google.auth.transport.grpc.SslCredentials class.
- mock_ssl_cred = mock.Mock()
- with mock.patch.multiple(
- "google.auth.transport.grpc.SslCredentials",
- __init__=mock.Mock(return_value=None),
- ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
- ):
- mock_cred = mock.Mock()
- transport = transports.GameServerDeploymentsServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint=api_mtls_endpoint,
- client_cert_source=None,
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-def test_game_server_deployments_service_grpc_lro_client():
- client = GameServerDeploymentsServiceClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc"
- )
- transport = client._transport
-
- # Ensure that we have a api-core operations client.
- assert isinstance(transport.operations_client, operations_v1.OperationsClient)
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
-
-
-def test_game_server_deployment_rollout_path():
- project = "squid"
- location = "clam"
- deployment = "whelk"
-
- expected = "projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout".format(
- project=project, location=location, deployment=deployment
- )
- actual = GameServerDeploymentsServiceClient.game_server_deployment_rollout_path(
- project, location, deployment
- )
- assert expected == actual
-
-
-def test_parse_game_server_deployment_rollout_path():
- expected = {"project": "octopus", "location": "oyster", "deployment": "nudibranch"}
- path = GameServerDeploymentsServiceClient.game_server_deployment_rollout_path(
- **expected
- )
-
- # Check that the path construction is reversible.
- actual = GameServerDeploymentsServiceClient.parse_game_server_deployment_rollout_path(
- path
- )
- assert expected == actual
-
-
-def test_game_server_deployment_path():
- project = "squid"
- location = "clam"
- deployment = "whelk"
-
- expected = "projects/{project}/locations/{location}/gameServerDeployments/{deployment}".format(
- project=project, location=location, deployment=deployment
- )
- actual = GameServerDeploymentsServiceClient.game_server_deployment_path(
- project, location, deployment
- )
- assert expected == actual
-
-
-def test_parse_game_server_deployment_path():
- expected = {"project": "octopus", "location": "oyster", "deployment": "nudibranch"}
- path = GameServerDeploymentsServiceClient.game_server_deployment_path(**expected)
-
- # Check that the path construction is reversible.
- actual = GameServerDeploymentsServiceClient.parse_game_server_deployment_path(path)
- assert expected == actual
diff --git a/tests/unit/gaming_v1/test_realms_service.py b/tests/unit/gaming_v1/test_realms_service.py
deleted file mode 100644
index 5223a020..00000000
--- a/tests/unit/gaming_v1/test_realms_service.py
+++ /dev/null
@@ -1,792 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from unittest import mock
-
-import grpc
-import math
-import pytest
-
-from google import auth
-from google.api_core import client_options
-from google.api_core import future
-from google.api_core import grpc_helpers
-from google.api_core import operations_v1
-from google.auth import credentials
-from google.cloud.gaming_v1.services.realms_service import RealmsServiceClient
-from google.cloud.gaming_v1.services.realms_service import pagers
-from google.cloud.gaming_v1.services.realms_service import transports
-from google.cloud.gaming_v1.types import common
-from google.cloud.gaming_v1.types import realms
-from google.longrunning import operations_pb2
-from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
-
-def client_cert_source_callback():
- return b"cert bytes", b"key bytes"
-
-
-def test__get_default_mtls_endpoint():
- api_endpoint = "example.googleapis.com"
- api_mtls_endpoint = "example.mtls.googleapis.com"
- sandbox_endpoint = "example.sandbox.googleapis.com"
- sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
- non_googleapi = "api.example.com"
-
- assert RealmsServiceClient._get_default_mtls_endpoint(None) is None
- assert (
- RealmsServiceClient._get_default_mtls_endpoint(api_endpoint)
- == api_mtls_endpoint
- )
- assert (
- RealmsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
- == api_mtls_endpoint
- )
- assert (
- RealmsServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- RealmsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- RealmsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
- )
-
-
-def test_realms_service_client_from_service_account_file():
- creds = credentials.AnonymousCredentials()
- with mock.patch.object(
- service_account.Credentials, "from_service_account_file"
- ) as factory:
- factory.return_value = creds
- client = RealmsServiceClient.from_service_account_file("dummy/file/path.json")
- assert client._transport._credentials == creds
-
- client = RealmsServiceClient.from_service_account_json("dummy/file/path.json")
- assert client._transport._credentials == creds
-
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_realms_service_client_client_options():
- # Check that if channel is provided we won't create a new one.
- with mock.patch(
- "google.cloud.gaming_v1.services.realms_service.RealmsServiceClient.get_transport_class"
- ) as gtc:
- transport = transports.RealmsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = RealmsServiceClient(transport=transport)
- gtc.assert_not_called()
-
- # Check mTLS is not triggered with empty client options.
- options = client_options.ClientOptions()
- with mock.patch(
- "google.cloud.gaming_v1.services.realms_service.RealmsServiceClient.get_transport_class"
- ) as gtc:
- transport = gtc.return_value = mock.MagicMock()
- client = RealmsServiceClient(client_options=options)
- transport.assert_called_once_with(
- credentials=None, host=client.DEFAULT_ENDPOINT
- )
-
- # Check mTLS is not triggered if api_endpoint is provided but
- # client_cert_source is None.
- options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
- with mock.patch(
- "google.cloud.gaming_v1.services.realms_service.transports.RealmsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = RealmsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
- # Check mTLS is triggered if client_cert_source is provided.
- options = client_options.ClientOptions(
- client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.realms_service.transports.RealmsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = RealmsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host=client.DEFAULT_ENDPOINT,
- )
-
- # Check mTLS is triggered if api_endpoint and client_cert_source are provided.
- options = client_options.ClientOptions(
- api_endpoint="squid.clam.whelk", client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.gaming_v1.services.realms_service.transports.RealmsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = RealmsServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint="squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_realms_service_client_client_options_from_dict():
- with mock.patch(
- "google.cloud.gaming_v1.services.realms_service.transports.RealmsServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = RealmsServiceClient(
- client_options={"api_endpoint": "squid.clam.whelk"}
- )
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_list_realms(transport: str = "grpc"):
- client = RealmsServiceClient(
- credentials=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 = realms.ListRealmsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = realms.ListRealmsResponse(
- next_page_token="next_page_token_value", unreachable=["unreachable_value"]
- )
-
- response = client.list_realms(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, pagers.ListRealmsPager)
- assert response.next_page_token == "next_page_token_value"
- assert response.unreachable == ["unreachable_value"]
-
-
-def test_list_realms_field_headers():
- client = RealmsServiceClient(credentials=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 = realms.ListRealmsRequest(parent="parent/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
- call.return_value = realms.ListRealmsResponse()
- client.list_realms(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"]
-
-
-def test_list_realms_flattened():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = realms.ListRealmsResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.list_realms(parent="parent_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].parent == "parent_value"
-
-
-def test_list_realms_flattened_error():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.list_realms(realms.ListRealmsRequest(), parent="parent_value")
-
-
-def test_list_realms_pager():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
- # Set the response to a series of pages.
- call.side_effect = (
- realms.ListRealmsResponse(
- realms=[realms.Realm(), realms.Realm(), realms.Realm()],
- next_page_token="abc",
- ),
- realms.ListRealmsResponse(realms=[], next_page_token="def"),
- realms.ListRealmsResponse(realms=[realms.Realm()], next_page_token="ghi"),
- realms.ListRealmsResponse(realms=[realms.Realm(), realms.Realm()]),
- RuntimeError,
- )
- results = [i for i in client.list_realms(request={})]
- assert len(results) == 6
- assert all(isinstance(i, realms.Realm) for i in results)
-
-
-def test_list_realms_pages():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
- # Set the response to a series of pages.
- call.side_effect = (
- realms.ListRealmsResponse(
- realms=[realms.Realm(), realms.Realm(), realms.Realm()],
- next_page_token="abc",
- ),
- realms.ListRealmsResponse(realms=[], next_page_token="def"),
- realms.ListRealmsResponse(realms=[realms.Realm()], next_page_token="ghi"),
- realms.ListRealmsResponse(realms=[realms.Realm(), realms.Realm()]),
- RuntimeError,
- )
- pages = list(client.list_realms(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_get_realm(transport: str = "grpc"):
- client = RealmsServiceClient(
- credentials=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 = realms.GetRealmRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.get_realm), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = realms.Realm(
- name="name_value",
- time_zone="time_zone_value",
- etag="etag_value",
- description="description_value",
- )
-
- response = client.get_realm(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, realms.Realm)
- assert response.name == "name_value"
- assert response.time_zone == "time_zone_value"
- assert response.etag == "etag_value"
- assert response.description == "description_value"
-
-
-def test_get_realm_field_headers():
- client = RealmsServiceClient(credentials=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 = realms.GetRealmRequest(name="name/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.get_realm), "__call__") as call:
- call.return_value = realms.Realm()
- client.get_realm(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"]
-
-
-def test_get_realm_flattened():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.get_realm), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = realms.Realm()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_realm(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_get_realm_flattened_error():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.get_realm(realms.GetRealmRequest(), name="name_value")
-
-
-def test_create_realm(transport: str = "grpc"):
- client = RealmsServiceClient(
- credentials=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 = realms.CreateRealmRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.create_realm), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.create_realm(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, future.Future)
-
-
-def test_create_realm_flattened():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.create_realm), "__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.
- response = client.create_realm(
- parent="parent_value",
- realm=realms.Realm(name="name_value"),
- realm_id="realm_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]
- assert args[0].parent == "parent_value"
- assert args[0].realm == realms.Realm(name="name_value")
- assert args[0].realm_id == "realm_id_value"
-
-
-def test_create_realm_flattened_error():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.create_realm(
- realms.CreateRealmRequest(),
- parent="parent_value",
- realm=realms.Realm(name="name_value"),
- realm_id="realm_id_value",
- )
-
-
-def test_delete_realm(transport: str = "grpc"):
- client = RealmsServiceClient(
- credentials=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 = realms.DeleteRealmRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.delete_realm), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.delete_realm(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, future.Future)
-
-
-def test_delete_realm_flattened():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.delete_realm), "__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.
- response = client.delete_realm(name="name_value")
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
-
-
-def test_delete_realm_flattened_error():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.delete_realm(realms.DeleteRealmRequest(), name="name_value")
-
-
-def test_update_realm(transport: str = "grpc"):
- client = RealmsServiceClient(
- credentials=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 = realms.UpdateRealmRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.update_realm), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
-
- response = client.update_realm(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, future.Future)
-
-
-def test_update_realm_flattened():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.update_realm), "__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.
- response = client.update_realm(
- realm=realms.Realm(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].realm == realms.Realm(name="name_value")
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
-
-
-def test_update_realm_flattened_error():
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.update_realm(
- realms.UpdateRealmRequest(),
- realm=realms.Realm(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_preview_realm_update(transport: str = "grpc"):
- client = RealmsServiceClient(
- credentials=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 = realms.PreviewRealmUpdateRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.preview_realm_update), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = realms.PreviewRealmUpdateResponse(etag="etag_value")
-
- response = client.preview_realm_update(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, realms.PreviewRealmUpdateResponse)
- assert response.etag == "etag_value"
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.RealmsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- with pytest.raises(ValueError):
- client = RealmsServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.RealmsServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = RealmsServiceClient(transport=transport)
- assert client._transport is transport
-
-
-def test_transport_grpc_default():
- # A client should use the gRPC transport by default.
- client = RealmsServiceClient(credentials=credentials.AnonymousCredentials())
- assert isinstance(client._transport, transports.RealmsServiceGrpcTransport)
-
-
-def test_realms_service_base_transport():
- # Instantiate the base transport.
- transport = transports.RealmsServiceTransport(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Every method on the transport should just blindly
- # raise NotImplementedError.
- methods = (
- "list_realms",
- "get_realm",
- "create_realm",
- "delete_realm",
- "update_realm",
- "preview_realm_update",
- )
- for method in methods:
- with pytest.raises(NotImplementedError):
- getattr(transport, method)(request=object())
-
- # Additionally, the LRO client (a property) should
- # also raise NotImplementedError
- with pytest.raises(NotImplementedError):
- transport.operations_client
-
-
-def test_realms_service_auth_adc():
- # If no credentials are provided, we should use ADC credentials.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
- RealmsServiceClient()
- adc.assert_called_once_with(
- scopes=("https://www.googleapis.com/auth/cloud-platform",)
- )
-
-
-def test_realms_service_host_no_port():
- client = RealmsServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:443"
-
-
-def test_realms_service_host_with_port():
- client = RealmsServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="gameservices.googleapis.com:8000"
- ),
- transport="grpc",
- )
- assert client._transport._host == "gameservices.googleapis.com:8000"
-
-
-def test_realms_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
-
- # Check that if channel is provided, mtls endpoint and client_cert_source
- # won't be used.
- callback = mock.MagicMock()
- transport = transports.RealmsServiceGrpcTransport(
- host="squid.clam.whelk",
- channel=channel,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=callback,
- )
- assert transport.grpc_channel == channel
- assert transport._host == "squid.clam.whelk:443"
- assert not callback.called
-
-
-@mock.patch("grpc.ssl_channel_credentials", autospec=True)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_realms_service_grpc_transport_channel_mtls_with_client_cert_source(
- grpc_create_channel, grpc_ssl_channel_cred
-):
- # Check that if channel is None, but api_mtls_endpoint and client_cert_source
- # are provided, then a mTLS channel will be created.
- mock_cred = mock.Mock()
-
- mock_ssl_cred = mock.Mock()
- grpc_ssl_channel_cred.return_value = mock_ssl_cred
-
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- transport = transports.RealmsServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- )
- grpc_ssl_channel_cred.assert_called_once_with(
- certificate_chain=b"cert bytes", private_key=b"key bytes"
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-@pytest.mark.parametrize(
- "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
-)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_realms_service_grpc_transport_channel_mtls_with_adc(
- grpc_create_channel, api_mtls_endpoint
-):
- # Check that if channel and client_cert_source are None, but api_mtls_endpoint
- # is provided, then a mTLS channel will be created with SSL ADC.
- mock_grpc_channel = mock.Mock()
- grpc_create_channel.return_value = mock_grpc_channel
-
- # Mock google.auth.transport.grpc.SslCredentials class.
- mock_ssl_cred = mock.Mock()
- with mock.patch.multiple(
- "google.auth.transport.grpc.SslCredentials",
- __init__=mock.Mock(return_value=None),
- ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
- ):
- mock_cred = mock.Mock()
- transport = transports.RealmsServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint=api_mtls_endpoint,
- client_cert_source=None,
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=("https://www.googleapis.com/auth/cloud-platform",),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-def test_realms_service_grpc_lro_client():
- client = RealmsServiceClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc"
- )
- transport = client._transport
-
- # Ensure that we have a api-core operations client.
- assert isinstance(transport.operations_client, operations_v1.OperationsClient)
-
- # Ensure that subsequent calls to the property send the exact same object.
- assert transport.operations_client is transport.operations_client
-
-
-def test_realm_path():
- project = "squid"
- location = "clam"
- realm = "whelk"
-
- expected = "projects/{project}/locations/{location}/realms/{realm}".format(
- project=project, location=location, realm=realm
- )
- actual = RealmsServiceClient.realm_path(project, location, realm)
- assert expected == actual
-
-
-def test_parse_realm_path():
- expected = {"project": "octopus", "location": "oyster", "realm": "nudibranch"}
- path = RealmsServiceClient.realm_path(**expected)
-
- # Check that the path construction is reversible.
- actual = RealmsServiceClient.parse_realm_path(path)
- assert expected == actual
diff --git a/tests/unit/gapic/gaming_v1/test_game_server_clusters_service.py b/tests/unit/gapic/gaming_v1/test_game_server_clusters_service.py
new file mode 100644
index 00000000..d6fa8fb8
--- /dev/null
+++ b/tests/unit/gapic/gaming_v1/test_game_server_clusters_service.py
@@ -0,0 +1,2394 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.gaming_v1.services.game_server_clusters_service import (
+ GameServerClustersServiceAsyncClient,
+)
+from google.cloud.gaming_v1.services.game_server_clusters_service import (
+ GameServerClustersServiceClient,
+)
+from google.cloud.gaming_v1.services.game_server_clusters_service import pagers
+from google.cloud.gaming_v1.services.game_server_clusters_service import transports
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import game_server_clusters
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+def test__get_default_mtls_endpoint():
+ api_endpoint = "example.googleapis.com"
+ api_mtls_endpoint = "example.mtls.googleapis.com"
+ sandbox_endpoint = "example.sandbox.googleapis.com"
+ sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
+ non_googleapi = "api.example.com"
+
+ assert GameServerClustersServiceClient._get_default_mtls_endpoint(None) is None
+ assert (
+ GameServerClustersServiceClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ GameServerClustersServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ GameServerClustersServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ GameServerClustersServiceClient._get_default_mtls_endpoint(
+ sandbox_mtls_endpoint
+ )
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ GameServerClustersServiceClient._get_default_mtls_endpoint(non_googleapi)
+ == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class",
+ [GameServerClustersServiceClient, GameServerClustersServiceAsyncClient],
+)
+def test_game_server_clusters_service_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_game_server_clusters_service_client_get_transport_class():
+ transport = GameServerClustersServiceClient.get_transport_class()
+ assert transport == transports.GameServerClustersServiceGrpcTransport
+
+ transport = GameServerClustersServiceClient.get_transport_class("grpc")
+ assert transport == transports.GameServerClustersServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerClustersServiceClient,
+ transports.GameServerClustersServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerClustersServiceAsyncClient,
+ transports.GameServerClustersServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_clusters_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(
+ GameServerClustersServiceClient, "get_transport_class"
+ ) as gtc:
+ transport = transport_class(credentials=credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(
+ GameServerClustersServiceClient, "get_transport_class"
+ ) as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "never".
+ os.environ["GOOGLE_API_USE_MTLS"] = "never"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "always".
+ os.environ["GOOGLE_API_USE_MTLS"] = "always"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=client_cert_source_callback,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and default_client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", but client_cert_source and default_client_cert_source are None.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has
+ # unsupported value.
+ os.environ["GOOGLE_API_USE_MTLS"] = "Unsupported"
+ with pytest.raises(MutualTLSChannelError):
+ client = client_class()
+
+ del os.environ["GOOGLE_API_USE_MTLS"]
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerClustersServiceClient,
+ transports.GameServerClustersServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerClustersServiceAsyncClient,
+ transports.GameServerClustersServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_clusters_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=["1", "2"],
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerClustersServiceClient,
+ transports.GameServerClustersServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerClustersServiceAsyncClient,
+ transports.GameServerClustersServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_clusters_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+def test_game_server_clusters_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.gaming_v1.services.game_server_clusters_service.transports.GameServerClustersServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = GameServerClustersServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+
+def test_list_game_server_clusters(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.ListGameServerClustersRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.ListGameServerClustersResponse(
+ next_page_token="next_page_token_value", unreachable=["unreachable_value"],
+ )
+
+ response = client.list_game_server_clusters(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, pagers.ListGameServerClustersPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_clusters_async(transport: str = "grpc_asyncio"):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.ListGameServerClustersRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.ListGameServerClustersResponse(
+ next_page_token="next_page_token_value",
+ unreachable=["unreachable_value"],
+ )
+ )
+
+ response = await client.list_game_server_clusters(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 response is the type that we expect.
+ assert isinstance(response, pagers.ListGameServerClustersAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+def test_list_game_server_clusters_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.ListGameServerClustersRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ call.return_value = game_server_clusters.ListGameServerClustersResponse()
+
+ client.list_game_server_clusters(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_game_server_clusters_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.ListGameServerClustersRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.ListGameServerClustersResponse()
+ )
+
+ await client.list_game_server_clusters(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_game_server_clusters_flattened():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.ListGameServerClustersResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_game_server_clusters(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+def test_list_game_server_clusters_flattened_error():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_game_server_clusters(
+ game_server_clusters.ListGameServerClustersRequest(), parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_clusters_flattened_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.ListGameServerClustersResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.ListGameServerClustersResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_game_server_clusters(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_clusters_flattened_error_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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_game_server_clusters(
+ game_server_clusters.ListGameServerClustersRequest(), parent="parent_value",
+ )
+
+
+def test_list_game_server_clusters_pager():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[], next_page_token="def",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[game_server_clusters.GameServerCluster(),],
+ next_page_token="ghi",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_game_server_clusters(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(
+ isinstance(i, game_server_clusters.GameServerCluster) for i in results
+ )
+
+
+def test_list_game_server_clusters_pages():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_clusters), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[], next_page_token="def",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[game_server_clusters.GameServerCluster(),],
+ next_page_token="ghi",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_game_server_clusters(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_game_server_clusters_async_pager():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_clusters),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[], next_page_token="def",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[game_server_clusters.GameServerCluster(),],
+ next_page_token="ghi",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_game_server_clusters(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(
+ isinstance(i, game_server_clusters.GameServerCluster) for i in responses
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_clusters_async_pages():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_clusters),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[], next_page_token="def",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[game_server_clusters.GameServerCluster(),],
+ next_page_token="ghi",
+ ),
+ game_server_clusters.ListGameServerClustersResponse(
+ game_server_clusters=[
+ game_server_clusters.GameServerCluster(),
+ game_server_clusters.GameServerCluster(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.list_game_server_clusters(request={})).pages:
+ pages.append(page)
+ for page, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page.raw_page.next_page_token == token
+
+
+def test_get_game_server_cluster(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.GetGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.GameServerCluster(
+ name="name_value", etag="etag_value", description="description_value",
+ )
+
+ response = client.get_game_server_cluster(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, game_server_clusters.GameServerCluster)
+
+ assert response.name == "name_value"
+
+ assert response.etag == "etag_value"
+
+ assert response.description == "description_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_cluster_async(transport: str = "grpc_asyncio"):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.GetGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.GameServerCluster(
+ name="name_value", etag="etag_value", description="description_value",
+ )
+ )
+
+ response = await client.get_game_server_cluster(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 response is the type that we expect.
+ assert isinstance(response, game_server_clusters.GameServerCluster)
+
+ assert response.name == "name_value"
+
+ assert response.etag == "etag_value"
+
+ assert response.description == "description_value"
+
+
+def test_get_game_server_cluster_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.GetGameServerClusterRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = game_server_clusters.GameServerCluster()
+
+ client.get_game_server_cluster(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_game_server_cluster_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.GetGameServerClusterRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.GameServerCluster()
+ )
+
+ await client.get_game_server_cluster(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_game_server_cluster_flattened():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.GameServerCluster()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_game_server_cluster(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_get_game_server_cluster_flattened_error():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_game_server_cluster(
+ game_server_clusters.GetGameServerClusterRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_cluster_flattened_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.GameServerCluster()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.GameServerCluster()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_game_server_cluster(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_cluster_flattened_error_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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_game_server_cluster(
+ game_server_clusters.GetGameServerClusterRequest(), name="name_value",
+ )
+
+
+def test_create_game_server_cluster(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.CreateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.create_game_server_cluster(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_cluster_async(transport: str = "grpc_asyncio"):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.CreateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_cluster), "__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_game_server_cluster(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_game_server_cluster_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.CreateGameServerClusterRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.create_game_server_cluster(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_game_server_cluster_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.CreateGameServerClusterRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.create_game_server_cluster(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_game_server_cluster_flattened():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_cluster), "__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_game_server_cluster(
+ parent="parent_value",
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ game_server_cluster_id="game_server_cluster_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]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].game_server_cluster == game_server_clusters.GameServerCluster(
+ name="name_value"
+ )
+
+ assert args[0].game_server_cluster_id == "game_server_cluster_id_value"
+
+
+def test_create_game_server_cluster_flattened_error():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.create_game_server_cluster(
+ game_server_clusters.CreateGameServerClusterRequest(),
+ parent="parent_value",
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ game_server_cluster_id="game_server_cluster_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_cluster_flattened_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_cluster), "__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_game_server_cluster(
+ parent="parent_value",
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ game_server_cluster_id="game_server_cluster_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]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].game_server_cluster == game_server_clusters.GameServerCluster(
+ name="name_value"
+ )
+
+ assert args[0].game_server_cluster_id == "game_server_cluster_id_value"
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_cluster_flattened_error_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.create_game_server_cluster(
+ game_server_clusters.CreateGameServerClusterRequest(),
+ parent="parent_value",
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ game_server_cluster_id="game_server_cluster_id_value",
+ )
+
+
+def test_preview_create_game_server_cluster(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.PreviewCreateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_create_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.PreviewCreateGameServerClusterResponse(
+ etag="etag_value",
+ )
+
+ response = client.preview_create_game_server_cluster(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, game_server_clusters.PreviewCreateGameServerClusterResponse
+ )
+
+ assert response.etag == "etag_value"
+
+
+@pytest.mark.asyncio
+async def test_preview_create_game_server_cluster_async(
+ transport: str = "grpc_asyncio",
+):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.PreviewCreateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_create_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.PreviewCreateGameServerClusterResponse(
+ etag="etag_value",
+ )
+ )
+
+ response = await client.preview_create_game_server_cluster(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 response is the type that we expect.
+ assert isinstance(
+ response, game_server_clusters.PreviewCreateGameServerClusterResponse
+ )
+
+ assert response.etag == "etag_value"
+
+
+def test_preview_create_game_server_cluster_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.PreviewCreateGameServerClusterRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_create_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = (
+ game_server_clusters.PreviewCreateGameServerClusterResponse()
+ )
+
+ client.preview_create_game_server_cluster(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_preview_create_game_server_cluster_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.PreviewCreateGameServerClusterRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_create_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.PreviewCreateGameServerClusterResponse()
+ )
+
+ await client.preview_create_game_server_cluster(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_delete_game_server_cluster(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.DeleteGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_game_server_cluster(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_cluster_async(transport: str = "grpc_asyncio"):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.DeleteGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_cluster), "__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_game_server_cluster(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_game_server_cluster_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.DeleteGameServerClusterRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_game_server_cluster(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_game_server_cluster_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.DeleteGameServerClusterRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_game_server_cluster(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_game_server_cluster_flattened():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_cluster), "__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_game_server_cluster(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_delete_game_server_cluster_flattened_error():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_game_server_cluster(
+ game_server_clusters.DeleteGameServerClusterRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_cluster_flattened_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_cluster), "__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_game_server_cluster(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_cluster_flattened_error_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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_game_server_cluster(
+ game_server_clusters.DeleteGameServerClusterRequest(), name="name_value",
+ )
+
+
+def test_preview_delete_game_server_cluster(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.PreviewDeleteGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_delete_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.PreviewDeleteGameServerClusterResponse(
+ etag="etag_value",
+ )
+
+ response = client.preview_delete_game_server_cluster(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, game_server_clusters.PreviewDeleteGameServerClusterResponse
+ )
+
+ assert response.etag == "etag_value"
+
+
+@pytest.mark.asyncio
+async def test_preview_delete_game_server_cluster_async(
+ transport: str = "grpc_asyncio",
+):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.PreviewDeleteGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_delete_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.PreviewDeleteGameServerClusterResponse(
+ etag="etag_value",
+ )
+ )
+
+ response = await client.preview_delete_game_server_cluster(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 response is the type that we expect.
+ assert isinstance(
+ response, game_server_clusters.PreviewDeleteGameServerClusterResponse
+ )
+
+ assert response.etag == "etag_value"
+
+
+def test_preview_delete_game_server_cluster_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.PreviewDeleteGameServerClusterRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_delete_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = (
+ game_server_clusters.PreviewDeleteGameServerClusterResponse()
+ )
+
+ client.preview_delete_game_server_cluster(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_preview_delete_game_server_cluster_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.PreviewDeleteGameServerClusterRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_delete_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.PreviewDeleteGameServerClusterResponse()
+ )
+
+ await client.preview_delete_game_server_cluster(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_game_server_cluster(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.UpdateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_game_server_cluster(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_cluster_async(transport: str = "grpc_asyncio"):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.UpdateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_cluster), "__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.update_game_server_cluster(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_game_server_cluster_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.UpdateGameServerClusterRequest()
+ request.game_server_cluster.name = "game_server_cluster.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_game_server_cluster(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",
+ "game_server_cluster.name=game_server_cluster.name/value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_cluster_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.UpdateGameServerClusterRequest()
+ request.game_server_cluster.name = "game_server_cluster.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_game_server_cluster(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",
+ "game_server_cluster.name=game_server_cluster.name/value",
+ ) in kw["metadata"]
+
+
+def test_update_game_server_cluster_flattened():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_cluster), "__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.update_game_server_cluster(
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].game_server_cluster == game_server_clusters.GameServerCluster(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_game_server_cluster_flattened_error():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_game_server_cluster(
+ game_server_clusters.UpdateGameServerClusterRequest(),
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_cluster_flattened_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_cluster), "__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.update_game_server_cluster(
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].game_server_cluster == game_server_clusters.GameServerCluster(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_cluster_flattened_error_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.update_game_server_cluster(
+ game_server_clusters.UpdateGameServerClusterRequest(),
+ game_server_cluster=game_server_clusters.GameServerCluster(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_preview_update_game_server_cluster(transport: str = "grpc"):
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.PreviewUpdateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_update_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_clusters.PreviewUpdateGameServerClusterResponse(
+ etag="etag_value",
+ )
+
+ response = client.preview_update_game_server_cluster(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, game_server_clusters.PreviewUpdateGameServerClusterResponse
+ )
+
+ assert response.etag == "etag_value"
+
+
+@pytest.mark.asyncio
+async def test_preview_update_game_server_cluster_async(
+ transport: str = "grpc_asyncio",
+):
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.PreviewUpdateGameServerClusterRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_update_game_server_cluster), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.PreviewUpdateGameServerClusterResponse(
+ etag="etag_value",
+ )
+ )
+
+ response = await client.preview_update_game_server_cluster(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 response is the type that we expect.
+ assert isinstance(
+ response, game_server_clusters.PreviewUpdateGameServerClusterResponse
+ )
+
+ assert response.etag == "etag_value"
+
+
+def test_preview_update_game_server_cluster_field_headers():
+ client = GameServerClustersServiceClient(
+ credentials=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 = game_server_clusters.PreviewUpdateGameServerClusterRequest()
+ request.game_server_cluster.name = "game_server_cluster.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_update_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = (
+ game_server_clusters.PreviewUpdateGameServerClusterResponse()
+ )
+
+ client.preview_update_game_server_cluster(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",
+ "game_server_cluster.name=game_server_cluster.name/value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_preview_update_game_server_cluster_field_headers_async():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=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 = game_server_clusters.PreviewUpdateGameServerClusterRequest()
+ request.game_server_cluster.name = "game_server_cluster.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_update_game_server_cluster), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_clusters.PreviewUpdateGameServerClusterResponse()
+ )
+
+ await client.preview_update_game_server_cluster(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",
+ "game_server_cluster.name=game_server_cluster.name/value",
+ ) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerClustersServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerClustersServiceClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = GameServerClustersServiceClient(transport=transport)
+ assert client._transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.GameServerClustersServiceGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client._transport, transports.GameServerClustersServiceGrpcTransport,
+ )
+
+
+def test_game_server_clusters_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.GameServerClustersServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_game_server_clusters_service_base_transport():
+ # Instantiate the base transport.
+ transport = transports.GameServerClustersServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_game_server_clusters",
+ "get_game_server_cluster",
+ "create_game_server_cluster",
+ "preview_create_game_server_cluster",
+ "delete_game_server_cluster",
+ "preview_delete_game_server_cluster",
+ "update_game_server_cluster",
+ "preview_update_game_server_cluster",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_game_server_clusters_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(auth, "load_credentials_from_file") as load_creds:
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.GameServerClustersServiceTransport(
+ credentials_file="credentials.json",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ )
+
+
+def test_game_server_clusters_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ GameServerClustersServiceClient()
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_game_server_clusters_service_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.GameServerClustersServiceGrpcTransport(host="squid.clam.whelk")
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_game_server_clusters_service_host_no_port():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_game_server_clusters_service_host_with_port():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com:8000"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:8000"
+
+
+def test_game_server_clusters_service_grpc_transport_channel():
+ channel = grpc.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+def test_game_server_clusters_service_grpc_asyncio_transport_channel():
+ channel = aio.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.GameServerClustersServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_game_server_clusters_service_grpc_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_game_server_clusters_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.GameServerClustersServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_game_server_clusters_service_grpc_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.GameServerClustersServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_game_server_clusters_service_grpc_asyncio_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.GameServerClustersServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_game_server_clusters_service_grpc_lro_client():
+ client = GameServerClustersServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_game_server_clusters_service_grpc_lro_async_client():
+ client = GameServerClustersServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client._client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_game_server_cluster_path():
+ project = "squid"
+ location = "clam"
+ realm = "whelk"
+ cluster = "octopus"
+
+ expected = "projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}".format(
+ project=project, location=location, realm=realm, cluster=cluster,
+ )
+ actual = GameServerClustersServiceClient.game_server_cluster_path(
+ project, location, realm, cluster
+ )
+ assert expected == actual
+
+
+def test_parse_game_server_cluster_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ "realm": "cuttlefish",
+ "cluster": "mussel",
+ }
+ path = GameServerClustersServiceClient.game_server_cluster_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = GameServerClustersServiceClient.parse_game_server_cluster_path(path)
+ assert expected == actual
diff --git a/tests/unit/gapic/gaming_v1/test_game_server_configs_service.py b/tests/unit/gapic/gaming_v1/test_game_server_configs_service.py
new file mode 100644
index 00000000..e46830c3
--- /dev/null
+++ b/tests/unit/gapic/gaming_v1/test_game_server_configs_service.py
@@ -0,0 +1,1729 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.gaming_v1.services.game_server_configs_service import (
+ GameServerConfigsServiceAsyncClient,
+)
+from google.cloud.gaming_v1.services.game_server_configs_service import (
+ GameServerConfigsServiceClient,
+)
+from google.cloud.gaming_v1.services.game_server_configs_service import pagers
+from google.cloud.gaming_v1.services.game_server_configs_service import transports
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import game_server_configs
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import duration_pb2 as duration # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+def test__get_default_mtls_endpoint():
+ api_endpoint = "example.googleapis.com"
+ api_mtls_endpoint = "example.mtls.googleapis.com"
+ sandbox_endpoint = "example.sandbox.googleapis.com"
+ sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
+ non_googleapi = "api.example.com"
+
+ assert GameServerConfigsServiceClient._get_default_mtls_endpoint(None) is None
+ assert (
+ GameServerConfigsServiceClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ GameServerConfigsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ GameServerConfigsServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ GameServerConfigsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ GameServerConfigsServiceClient._get_default_mtls_endpoint(non_googleapi)
+ == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class",
+ [GameServerConfigsServiceClient, GameServerConfigsServiceAsyncClient],
+)
+def test_game_server_configs_service_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_game_server_configs_service_client_get_transport_class():
+ transport = GameServerConfigsServiceClient.get_transport_class()
+ assert transport == transports.GameServerConfigsServiceGrpcTransport
+
+ transport = GameServerConfigsServiceClient.get_transport_class("grpc")
+ assert transport == transports.GameServerConfigsServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerConfigsServiceClient,
+ transports.GameServerConfigsServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerConfigsServiceAsyncClient,
+ transports.GameServerConfigsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_configs_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(
+ GameServerConfigsServiceClient, "get_transport_class"
+ ) as gtc:
+ transport = transport_class(credentials=credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(
+ GameServerConfigsServiceClient, "get_transport_class"
+ ) as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "never".
+ os.environ["GOOGLE_API_USE_MTLS"] = "never"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "always".
+ os.environ["GOOGLE_API_USE_MTLS"] = "always"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=client_cert_source_callback,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and default_client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", but client_cert_source and default_client_cert_source are None.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has
+ # unsupported value.
+ os.environ["GOOGLE_API_USE_MTLS"] = "Unsupported"
+ with pytest.raises(MutualTLSChannelError):
+ client = client_class()
+
+ del os.environ["GOOGLE_API_USE_MTLS"]
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerConfigsServiceClient,
+ transports.GameServerConfigsServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerConfigsServiceAsyncClient,
+ transports.GameServerConfigsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_configs_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=["1", "2"],
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerConfigsServiceClient,
+ transports.GameServerConfigsServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerConfigsServiceAsyncClient,
+ transports.GameServerConfigsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_configs_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+def test_game_server_configs_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.gaming_v1.services.game_server_configs_service.transports.GameServerConfigsServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = GameServerConfigsServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+
+def test_list_game_server_configs(transport: str = "grpc"):
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.ListGameServerConfigsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_configs.ListGameServerConfigsResponse(
+ next_page_token="next_page_token_value", unreachable=["unreachable_value"],
+ )
+
+ response = client.list_game_server_configs(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, pagers.ListGameServerConfigsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_configs_async(transport: str = "grpc_asyncio"):
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.ListGameServerConfigsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_configs.ListGameServerConfigsResponse(
+ next_page_token="next_page_token_value",
+ unreachable=["unreachable_value"],
+ )
+ )
+
+ response = await client.list_game_server_configs(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 response is the type that we expect.
+ assert isinstance(response, pagers.ListGameServerConfigsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+def test_list_game_server_configs_field_headers():
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.ListGameServerConfigsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ call.return_value = game_server_configs.ListGameServerConfigsResponse()
+
+ client.list_game_server_configs(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_game_server_configs_field_headers_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.ListGameServerConfigsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_configs.ListGameServerConfigsResponse()
+ )
+
+ await client.list_game_server_configs(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_game_server_configs_flattened():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_configs.ListGameServerConfigsResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_game_server_configs(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+def test_list_game_server_configs_flattened_error():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_game_server_configs(
+ game_server_configs.ListGameServerConfigsRequest(), parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_configs_flattened_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_configs.ListGameServerConfigsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_configs.ListGameServerConfigsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_game_server_configs(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_configs_flattened_error_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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_game_server_configs(
+ game_server_configs.ListGameServerConfigsRequest(), parent="parent_value",
+ )
+
+
+def test_list_game_server_configs_pager():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[], next_page_token="def",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[game_server_configs.GameServerConfig(),],
+ next_page_token="ghi",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_game_server_configs(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, game_server_configs.GameServerConfig) for i in results)
+
+
+def test_list_game_server_configs_pages():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_configs), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[], next_page_token="def",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[game_server_configs.GameServerConfig(),],
+ next_page_token="ghi",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_game_server_configs(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_game_server_configs_async_pager():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_configs),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[], next_page_token="def",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[game_server_configs.GameServerConfig(),],
+ next_page_token="ghi",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_game_server_configs(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(
+ isinstance(i, game_server_configs.GameServerConfig) for i in responses
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_configs_async_pages():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_configs),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[], next_page_token="def",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[game_server_configs.GameServerConfig(),],
+ next_page_token="ghi",
+ ),
+ game_server_configs.ListGameServerConfigsResponse(
+ game_server_configs=[
+ game_server_configs.GameServerConfig(),
+ game_server_configs.GameServerConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.list_game_server_configs(request={})).pages:
+ pages.append(page)
+ for page, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page.raw_page.next_page_token == token
+
+
+def test_get_game_server_config(transport: str = "grpc"):
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.GetGameServerConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_configs.GameServerConfig(
+ name="name_value", description="description_value",
+ )
+
+ response = client.get_game_server_config(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, game_server_configs.GameServerConfig)
+
+ assert response.name == "name_value"
+
+ assert response.description == "description_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_config_async(transport: str = "grpc_asyncio"):
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.GetGameServerConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_configs.GameServerConfig(
+ name="name_value", description="description_value",
+ )
+ )
+
+ response = await client.get_game_server_config(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 response is the type that we expect.
+ assert isinstance(response, game_server_configs.GameServerConfig)
+
+ assert response.name == "name_value"
+
+ assert response.description == "description_value"
+
+
+def test_get_game_server_config_field_headers():
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.GetGameServerConfigRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_config), "__call__"
+ ) as call:
+ call.return_value = game_server_configs.GameServerConfig()
+
+ client.get_game_server_config(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_game_server_config_field_headers_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.GetGameServerConfigRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_configs.GameServerConfig()
+ )
+
+ await client.get_game_server_config(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_game_server_config_flattened():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_configs.GameServerConfig()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_game_server_config(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_get_game_server_config_flattened_error():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_game_server_config(
+ game_server_configs.GetGameServerConfigRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_config_flattened_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_configs.GameServerConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_configs.GameServerConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_game_server_config(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_config_flattened_error_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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_game_server_config(
+ game_server_configs.GetGameServerConfigRequest(), name="name_value",
+ )
+
+
+def test_create_game_server_config(transport: str = "grpc"):
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.CreateGameServerConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.create_game_server_config(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_config_async(transport: str = "grpc_asyncio"):
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.CreateGameServerConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_config), "__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_game_server_config(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_game_server_config_field_headers():
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.CreateGameServerConfigRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_config), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.create_game_server_config(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_game_server_config_field_headers_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.CreateGameServerConfigRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.create_game_server_config(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_game_server_config_flattened():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_config), "__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_game_server_config(
+ parent="parent_value",
+ game_server_config=game_server_configs.GameServerConfig(name="name_value"),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].game_server_config == game_server_configs.GameServerConfig(
+ name="name_value"
+ )
+
+
+def test_create_game_server_config_flattened_error():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.create_game_server_config(
+ game_server_configs.CreateGameServerConfigRequest(),
+ parent="parent_value",
+ game_server_config=game_server_configs.GameServerConfig(name="name_value"),
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_config_flattened_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_config), "__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_game_server_config(
+ parent="parent_value",
+ game_server_config=game_server_configs.GameServerConfig(name="name_value"),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].game_server_config == game_server_configs.GameServerConfig(
+ name="name_value"
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_config_flattened_error_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.create_game_server_config(
+ game_server_configs.CreateGameServerConfigRequest(),
+ parent="parent_value",
+ game_server_config=game_server_configs.GameServerConfig(name="name_value"),
+ )
+
+
+def test_delete_game_server_config(transport: str = "grpc"):
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.DeleteGameServerConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_game_server_config(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_config_async(transport: str = "grpc_asyncio"):
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.DeleteGameServerConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_config), "__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_game_server_config(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_game_server_config_field_headers():
+ client = GameServerConfigsServiceClient(
+ credentials=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 = game_server_configs.DeleteGameServerConfigRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_config), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_game_server_config(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_game_server_config_field_headers_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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 = game_server_configs.DeleteGameServerConfigRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_game_server_config(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_game_server_config_flattened():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_config), "__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_game_server_config(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_delete_game_server_config_flattened_error():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_game_server_config(
+ game_server_configs.DeleteGameServerConfigRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_config_flattened_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_config), "__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_game_server_config(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_config_flattened_error_async():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=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_game_server_config(
+ game_server_configs.DeleteGameServerConfigRequest(), name="name_value",
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerConfigsServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerConfigsServiceClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = GameServerConfigsServiceClient(transport=transport)
+ assert client._transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.GameServerConfigsServiceGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client._transport, transports.GameServerConfigsServiceGrpcTransport,
+ )
+
+
+def test_game_server_configs_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.GameServerConfigsServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_game_server_configs_service_base_transport():
+ # Instantiate the base transport.
+ transport = transports.GameServerConfigsServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_game_server_configs",
+ "get_game_server_config",
+ "create_game_server_config",
+ "delete_game_server_config",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_game_server_configs_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(auth, "load_credentials_from_file") as load_creds:
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.GameServerConfigsServiceTransport(
+ credentials_file="credentials.json",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ )
+
+
+def test_game_server_configs_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ GameServerConfigsServiceClient()
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_game_server_configs_service_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.GameServerConfigsServiceGrpcTransport(host="squid.clam.whelk")
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_game_server_configs_service_host_no_port():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_game_server_configs_service_host_with_port():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com:8000"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:8000"
+
+
+def test_game_server_configs_service_grpc_transport_channel():
+ channel = grpc.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+def test_game_server_configs_service_grpc_asyncio_transport_channel():
+ channel = aio.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.GameServerConfigsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_game_server_configs_service_grpc_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_game_server_configs_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.GameServerConfigsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_game_server_configs_service_grpc_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.GameServerConfigsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_game_server_configs_service_grpc_asyncio_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.GameServerConfigsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_game_server_configs_service_grpc_lro_client():
+ client = GameServerConfigsServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_game_server_configs_service_grpc_lro_async_client():
+ client = GameServerConfigsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client._client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_game_server_config_path():
+ project = "squid"
+ location = "clam"
+ deployment = "whelk"
+ config = "octopus"
+
+ expected = "projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}".format(
+ project=project, location=location, deployment=deployment, config=config,
+ )
+ actual = GameServerConfigsServiceClient.game_server_config_path(
+ project, location, deployment, config
+ )
+ assert expected == actual
+
+
+def test_parse_game_server_config_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ "deployment": "cuttlefish",
+ "config": "mussel",
+ }
+ path = GameServerConfigsServiceClient.game_server_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = GameServerConfigsServiceClient.parse_game_server_config_path(path)
+ assert expected == actual
diff --git a/tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py b/tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
new file mode 100644
index 00000000..35b19553
--- /dev/null
+++ b/tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
@@ -0,0 +1,2752 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.gaming_v1.services.game_server_deployments_service import (
+ GameServerDeploymentsServiceAsyncClient,
+)
+from google.cloud.gaming_v1.services.game_server_deployments_service import (
+ GameServerDeploymentsServiceClient,
+)
+from google.cloud.gaming_v1.services.game_server_deployments_service import pagers
+from google.cloud.gaming_v1.services.game_server_deployments_service import transports
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import game_server_deployments
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+def test__get_default_mtls_endpoint():
+ api_endpoint = "example.googleapis.com"
+ api_mtls_endpoint = "example.mtls.googleapis.com"
+ sandbox_endpoint = "example.sandbox.googleapis.com"
+ sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
+ non_googleapi = "api.example.com"
+
+ assert GameServerDeploymentsServiceClient._get_default_mtls_endpoint(None) is None
+ assert (
+ GameServerDeploymentsServiceClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ GameServerDeploymentsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ GameServerDeploymentsServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ GameServerDeploymentsServiceClient._get_default_mtls_endpoint(
+ sandbox_mtls_endpoint
+ )
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ GameServerDeploymentsServiceClient._get_default_mtls_endpoint(non_googleapi)
+ == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class",
+ [GameServerDeploymentsServiceClient, GameServerDeploymentsServiceAsyncClient],
+)
+def test_game_server_deployments_service_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_game_server_deployments_service_client_get_transport_class():
+ transport = GameServerDeploymentsServiceClient.get_transport_class()
+ assert transport == transports.GameServerDeploymentsServiceGrpcTransport
+
+ transport = GameServerDeploymentsServiceClient.get_transport_class("grpc")
+ assert transport == transports.GameServerDeploymentsServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerDeploymentsServiceClient,
+ transports.GameServerDeploymentsServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerDeploymentsServiceAsyncClient,
+ transports.GameServerDeploymentsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_deployments_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(
+ GameServerDeploymentsServiceClient, "get_transport_class"
+ ) as gtc:
+ transport = transport_class(credentials=credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(
+ GameServerDeploymentsServiceClient, "get_transport_class"
+ ) as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "never".
+ os.environ["GOOGLE_API_USE_MTLS"] = "never"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "always".
+ os.environ["GOOGLE_API_USE_MTLS"] = "always"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=client_cert_source_callback,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and default_client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", but client_cert_source and default_client_cert_source are None.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has
+ # unsupported value.
+ os.environ["GOOGLE_API_USE_MTLS"] = "Unsupported"
+ with pytest.raises(MutualTLSChannelError):
+ client = client_class()
+
+ del os.environ["GOOGLE_API_USE_MTLS"]
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerDeploymentsServiceClient,
+ transports.GameServerDeploymentsServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerDeploymentsServiceAsyncClient,
+ transports.GameServerDeploymentsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_deployments_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=["1", "2"],
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ GameServerDeploymentsServiceClient,
+ transports.GameServerDeploymentsServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ GameServerDeploymentsServiceAsyncClient,
+ transports.GameServerDeploymentsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_game_server_deployments_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+def test_game_server_deployments_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = GameServerDeploymentsServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+
+def test_list_game_server_deployments(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.ListGameServerDeploymentsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.ListGameServerDeploymentsResponse(
+ next_page_token="next_page_token_value", unreachable=["unreachable_value"],
+ )
+
+ response = client.list_game_server_deployments(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, pagers.ListGameServerDeploymentsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_deployments_async(transport: str = "grpc_asyncio"):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.ListGameServerDeploymentsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ next_page_token="next_page_token_value",
+ unreachable=["unreachable_value"],
+ )
+ )
+
+ response = await client.list_game_server_deployments(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 response is the type that we expect.
+ assert isinstance(response, pagers.ListGameServerDeploymentsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+def test_list_game_server_deployments_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.ListGameServerDeploymentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ call.return_value = game_server_deployments.ListGameServerDeploymentsResponse()
+
+ client.list_game_server_deployments(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_game_server_deployments_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.ListGameServerDeploymentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.ListGameServerDeploymentsResponse()
+ )
+
+ await client.list_game_server_deployments(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_game_server_deployments_flattened():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.ListGameServerDeploymentsResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_game_server_deployments(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+def test_list_game_server_deployments_flattened_error():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_game_server_deployments(
+ game_server_deployments.ListGameServerDeploymentsRequest(),
+ parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_deployments_flattened_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.ListGameServerDeploymentsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.ListGameServerDeploymentsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_game_server_deployments(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_deployments_flattened_error_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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_game_server_deployments(
+ game_server_deployments.ListGameServerDeploymentsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_game_server_deployments_pager():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[], next_page_token="def",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="ghi",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_game_server_deployments(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(
+ isinstance(i, game_server_deployments.GameServerDeployment) for i in results
+ )
+
+
+def test_list_game_server_deployments_pages():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_game_server_deployments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[], next_page_token="def",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="ghi",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_game_server_deployments(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_game_server_deployments_async_pager():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_deployments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[], next_page_token="def",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="ghi",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_game_server_deployments(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(
+ isinstance(i, game_server_deployments.GameServerDeployment)
+ for i in responses
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_game_server_deployments_async_pages():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_game_server_deployments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="abc",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[], next_page_token="def",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ ],
+ next_page_token="ghi",
+ ),
+ game_server_deployments.ListGameServerDeploymentsResponse(
+ game_server_deployments=[
+ game_server_deployments.GameServerDeployment(),
+ game_server_deployments.GameServerDeployment(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.list_game_server_deployments(request={})).pages:
+ pages.append(page)
+ for page, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page.raw_page.next_page_token == token
+
+
+def test_get_game_server_deployment(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_deployment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.GameServerDeployment(
+ name="name_value", etag="etag_value", description="description_value",
+ )
+
+ response = client.get_game_server_deployment(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, game_server_deployments.GameServerDeployment)
+
+ assert response.name == "name_value"
+
+ assert response.etag == "etag_value"
+
+ assert response.description == "description_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_deployment_async(transport: str = "grpc_asyncio"):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_deployment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.GameServerDeployment(
+ name="name_value", etag="etag_value", description="description_value",
+ )
+ )
+
+ response = await client.get_game_server_deployment(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 response is the type that we expect.
+ assert isinstance(response, game_server_deployments.GameServerDeployment)
+
+ assert response.name == "name_value"
+
+ assert response.etag == "etag_value"
+
+ assert response.description == "description_value"
+
+
+def test_get_game_server_deployment_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = game_server_deployments.GameServerDeployment()
+
+ client.get_game_server_deployment(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_game_server_deployment_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.GameServerDeployment()
+ )
+
+ await client.get_game_server_deployment(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_game_server_deployment_flattened():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_deployment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.GameServerDeployment()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_game_server_deployment(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_get_game_server_deployment_flattened_error():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_game_server_deployment(
+ game_server_deployments.GetGameServerDeploymentRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_deployment_flattened_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_deployment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.GameServerDeployment()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.GameServerDeployment()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_game_server_deployment(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_deployment_flattened_error_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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_game_server_deployment(
+ game_server_deployments.GetGameServerDeploymentRequest(), name="name_value",
+ )
+
+
+def test_create_game_server_deployment(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.CreateGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_deployment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.create_game_server_deployment(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_deployment_async(transport: str = "grpc_asyncio"):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.CreateGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_deployment), "__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_game_server_deployment(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_game_server_deployment_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.CreateGameServerDeploymentRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.create_game_server_deployment(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_game_server_deployment_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.CreateGameServerDeploymentRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.create_game_server_deployment(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_game_server_deployment_flattened():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_game_server_deployment), "__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_game_server_deployment(
+ parent="parent_value",
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[
+ 0
+ ].game_server_deployment == game_server_deployments.GameServerDeployment(
+ name="name_value"
+ )
+
+
+def test_create_game_server_deployment_flattened_error():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.create_game_server_deployment(
+ game_server_deployments.CreateGameServerDeploymentRequest(),
+ parent="parent_value",
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_deployment_flattened_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_game_server_deployment), "__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_game_server_deployment(
+ parent="parent_value",
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[
+ 0
+ ].game_server_deployment == game_server_deployments.GameServerDeployment(
+ name="name_value"
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_game_server_deployment_flattened_error_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.create_game_server_deployment(
+ game_server_deployments.CreateGameServerDeploymentRequest(),
+ parent="parent_value",
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ )
+
+
+def test_delete_game_server_deployment(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.DeleteGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_deployment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_game_server_deployment(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_deployment_async(transport: str = "grpc_asyncio"):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.DeleteGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_deployment), "__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_game_server_deployment(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_game_server_deployment_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.DeleteGameServerDeploymentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_game_server_deployment(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_game_server_deployment_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.DeleteGameServerDeploymentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_game_server_deployment(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_game_server_deployment_flattened():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_game_server_deployment), "__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_game_server_deployment(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_delete_game_server_deployment_flattened_error():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_game_server_deployment(
+ game_server_deployments.DeleteGameServerDeploymentRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_deployment_flattened_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_game_server_deployment), "__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_game_server_deployment(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_delete_game_server_deployment_flattened_error_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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_game_server_deployment(
+ game_server_deployments.DeleteGameServerDeploymentRequest(),
+ name="name_value",
+ )
+
+
+def test_update_game_server_deployment(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_deployment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_game_server_deployment(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_async(transport: str = "grpc_asyncio"):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_deployment), "__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.update_game_server_deployment(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_game_server_deployment_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRequest()
+ request.game_server_deployment.name = "game_server_deployment.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_game_server_deployment(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",
+ "game_server_deployment.name=game_server_deployment.name/value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRequest()
+ request.game_server_deployment.name = "game_server_deployment.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_deployment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_game_server_deployment(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",
+ "game_server_deployment.name=game_server_deployment.name/value",
+ ) in kw["metadata"]
+
+
+def test_update_game_server_deployment_flattened():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_deployment), "__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.update_game_server_deployment(
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[
+ 0
+ ].game_server_deployment == game_server_deployments.GameServerDeployment(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_game_server_deployment_flattened_error():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_game_server_deployment(
+ game_server_deployments.UpdateGameServerDeploymentRequest(),
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_flattened_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_deployment), "__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.update_game_server_deployment(
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[
+ 0
+ ].game_server_deployment == game_server_deployments.GameServerDeployment(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_flattened_error_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.update_game_server_deployment(
+ game_server_deployments.UpdateGameServerDeploymentRequest(),
+ game_server_deployment=game_server_deployments.GameServerDeployment(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_get_game_server_deployment_rollout(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRolloutRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_deployment_rollout), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.GameServerDeploymentRollout(
+ name="name_value",
+ default_game_server_config="default_game_server_config_value",
+ etag="etag_value",
+ )
+
+ response = client.get_game_server_deployment_rollout(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, game_server_deployments.GameServerDeploymentRollout)
+
+ assert response.name == "name_value"
+
+ assert response.default_game_server_config == "default_game_server_config_value"
+
+ assert response.etag == "etag_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_deployment_rollout_async(
+ transport: str = "grpc_asyncio",
+):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRolloutRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_deployment_rollout), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.GameServerDeploymentRollout(
+ name="name_value",
+ default_game_server_config="default_game_server_config_value",
+ etag="etag_value",
+ )
+ )
+
+ response = await client.get_game_server_deployment_rollout(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 response is the type that we expect.
+ assert isinstance(response, game_server_deployments.GameServerDeploymentRollout)
+
+ assert response.name == "name_value"
+
+ assert response.default_game_server_config == "default_game_server_config_value"
+
+ assert response.etag == "etag_value"
+
+
+def test_get_game_server_deployment_rollout_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRolloutRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_deployment_rollout), "__call__"
+ ) as call:
+ call.return_value = game_server_deployments.GameServerDeploymentRollout()
+
+ client.get_game_server_deployment_rollout(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_game_server_deployment_rollout_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.GetGameServerDeploymentRolloutRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_deployment_rollout), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.GameServerDeploymentRollout()
+ )
+
+ await client.get_game_server_deployment_rollout(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_game_server_deployment_rollout_flattened():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_game_server_deployment_rollout), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.GameServerDeploymentRollout()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_game_server_deployment_rollout(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_get_game_server_deployment_rollout_flattened_error():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_game_server_deployment_rollout(
+ game_server_deployments.GetGameServerDeploymentRolloutRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_deployment_rollout_flattened_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_game_server_deployment_rollout), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.GameServerDeploymentRollout()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.GameServerDeploymentRollout()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_game_server_deployment_rollout(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_get_game_server_deployment_rollout_flattened_error_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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_game_server_deployment_rollout(
+ game_server_deployments.GetGameServerDeploymentRolloutRequest(),
+ name="name_value",
+ )
+
+
+def test_update_game_server_deployment_rollout(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRolloutRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_deployment_rollout), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_game_server_deployment_rollout(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_rollout_async(
+ transport: str = "grpc_asyncio",
+):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRolloutRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_deployment_rollout),
+ "__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.update_game_server_deployment_rollout(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_game_server_deployment_rollout_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRolloutRequest()
+ request.rollout.name = "rollout.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_deployment_rollout), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_game_server_deployment_rollout(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", "rollout.name=rollout.name/value",) in kw[
+ "metadata"
+ ]
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_rollout_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.UpdateGameServerDeploymentRolloutRequest()
+ request.rollout.name = "rollout.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_deployment_rollout),
+ "__call__",
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_game_server_deployment_rollout(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", "rollout.name=rollout.name/value",) in kw[
+ "metadata"
+ ]
+
+
+def test_update_game_server_deployment_rollout_flattened():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_game_server_deployment_rollout), "__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.update_game_server_deployment_rollout(
+ rollout=game_server_deployments.GameServerDeploymentRollout(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].rollout == game_server_deployments.GameServerDeploymentRollout(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_game_server_deployment_rollout_flattened_error():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_game_server_deployment_rollout(
+ game_server_deployments.UpdateGameServerDeploymentRolloutRequest(),
+ rollout=game_server_deployments.GameServerDeploymentRollout(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_rollout_flattened_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_game_server_deployment_rollout),
+ "__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.update_game_server_deployment_rollout(
+ rollout=game_server_deployments.GameServerDeploymentRollout(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].rollout == game_server_deployments.GameServerDeploymentRollout(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_game_server_deployment_rollout_flattened_error_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.update_game_server_deployment_rollout(
+ game_server_deployments.UpdateGameServerDeploymentRolloutRequest(),
+ rollout=game_server_deployments.GameServerDeploymentRollout(
+ name="name_value"
+ ),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_preview_game_server_deployment_rollout(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.PreviewGameServerDeploymentRolloutRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_game_server_deployment_rollout), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.PreviewGameServerDeploymentRolloutResponse(
+ unavailable=["unavailable_value"], etag="etag_value",
+ )
+
+ response = client.preview_game_server_deployment_rollout(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, game_server_deployments.PreviewGameServerDeploymentRolloutResponse
+ )
+
+ assert response.unavailable == ["unavailable_value"]
+
+ assert response.etag == "etag_value"
+
+
+@pytest.mark.asyncio
+async def test_preview_game_server_deployment_rollout_async(
+ transport: str = "grpc_asyncio",
+):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.PreviewGameServerDeploymentRolloutRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_game_server_deployment_rollout),
+ "__call__",
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.PreviewGameServerDeploymentRolloutResponse(
+ unavailable=["unavailable_value"], etag="etag_value",
+ )
+ )
+
+ response = await client.preview_game_server_deployment_rollout(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 response is the type that we expect.
+ assert isinstance(
+ response, game_server_deployments.PreviewGameServerDeploymentRolloutResponse
+ )
+
+ assert response.unavailable == ["unavailable_value"]
+
+ assert response.etag == "etag_value"
+
+
+def test_preview_game_server_deployment_rollout_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.PreviewGameServerDeploymentRolloutRequest()
+ request.rollout.name = "rollout.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_game_server_deployment_rollout), "__call__"
+ ) as call:
+ call.return_value = (
+ game_server_deployments.PreviewGameServerDeploymentRolloutResponse()
+ )
+
+ client.preview_game_server_deployment_rollout(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", "rollout.name=rollout.name/value",) in kw[
+ "metadata"
+ ]
+
+
+@pytest.mark.asyncio
+async def test_preview_game_server_deployment_rollout_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.PreviewGameServerDeploymentRolloutRequest()
+ request.rollout.name = "rollout.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_game_server_deployment_rollout),
+ "__call__",
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.PreviewGameServerDeploymentRolloutResponse()
+ )
+
+ await client.preview_game_server_deployment_rollout(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", "rollout.name=rollout.name/value",) in kw[
+ "metadata"
+ ]
+
+
+def test_fetch_deployment_state(transport: str = "grpc"):
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.FetchDeploymentStateRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.fetch_deployment_state), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = game_server_deployments.FetchDeploymentStateResponse(
+ unavailable=["unavailable_value"],
+ )
+
+ response = client.fetch_deployment_state(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, game_server_deployments.FetchDeploymentStateResponse)
+
+ assert response.unavailable == ["unavailable_value"]
+
+
+@pytest.mark.asyncio
+async def test_fetch_deployment_state_async(transport: str = "grpc_asyncio"):
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.FetchDeploymentStateRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.fetch_deployment_state), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.FetchDeploymentStateResponse(
+ unavailable=["unavailable_value"],
+ )
+ )
+
+ response = await client.fetch_deployment_state(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 response is the type that we expect.
+ assert isinstance(response, game_server_deployments.FetchDeploymentStateResponse)
+
+ assert response.unavailable == ["unavailable_value"]
+
+
+def test_fetch_deployment_state_field_headers():
+ client = GameServerDeploymentsServiceClient(
+ credentials=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 = game_server_deployments.FetchDeploymentStateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.fetch_deployment_state), "__call__"
+ ) as call:
+ call.return_value = game_server_deployments.FetchDeploymentStateResponse()
+
+ client.fetch_deployment_state(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_fetch_deployment_state_field_headers_async():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=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 = game_server_deployments.FetchDeploymentStateRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.fetch_deployment_state), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ game_server_deployments.FetchDeploymentStateResponse()
+ )
+
+ await client.fetch_deployment_state(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerDeploymentsServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = GameServerDeploymentsServiceClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = GameServerDeploymentsServiceClient(transport=transport)
+ assert client._transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.GameServerDeploymentsServiceGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client._transport, transports.GameServerDeploymentsServiceGrpcTransport,
+ )
+
+
+def test_game_server_deployments_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.GameServerDeploymentsServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_game_server_deployments_service_base_transport():
+ # Instantiate the base transport.
+ transport = transports.GameServerDeploymentsServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_game_server_deployments",
+ "get_game_server_deployment",
+ "create_game_server_deployment",
+ "delete_game_server_deployment",
+ "update_game_server_deployment",
+ "get_game_server_deployment_rollout",
+ "update_game_server_deployment_rollout",
+ "preview_game_server_deployment_rollout",
+ "fetch_deployment_state",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_game_server_deployments_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(auth, "load_credentials_from_file") as load_creds:
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.GameServerDeploymentsServiceTransport(
+ credentials_file="credentials.json",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ )
+
+
+def test_game_server_deployments_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ GameServerDeploymentsServiceClient()
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_game_server_deployments_service_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.GameServerDeploymentsServiceGrpcTransport(host="squid.clam.whelk")
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_game_server_deployments_service_host_no_port():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_game_server_deployments_service_host_with_port():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com:8000"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:8000"
+
+
+def test_game_server_deployments_service_grpc_transport_channel():
+ channel = grpc.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+def test_game_server_deployments_service_grpc_asyncio_transport_channel():
+ channel = aio.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.GameServerDeploymentsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_game_server_deployments_service_grpc_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.GameServerDeploymentsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_game_server_deployments_service_grpc_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.GameServerDeploymentsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.GameServerDeploymentsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_game_server_deployments_service_grpc_lro_client():
+ client = GameServerDeploymentsServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_game_server_deployments_service_grpc_lro_async_client():
+ client = GameServerDeploymentsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client._client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_game_server_deployment_path():
+ project = "squid"
+ location = "clam"
+ deployment = "whelk"
+
+ expected = "projects/{project}/locations/{location}/gameServerDeployments/{deployment}".format(
+ project=project, location=location, deployment=deployment,
+ )
+ actual = GameServerDeploymentsServiceClient.game_server_deployment_path(
+ project, location, deployment
+ )
+ assert expected == actual
+
+
+def test_parse_game_server_deployment_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "deployment": "nudibranch",
+ }
+ path = GameServerDeploymentsServiceClient.game_server_deployment_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = GameServerDeploymentsServiceClient.parse_game_server_deployment_path(path)
+ assert expected == actual
+
+
+def test_game_server_deployment_rollout_path():
+ project = "squid"
+ location = "clam"
+ deployment = "whelk"
+
+ expected = "projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout".format(
+ project=project, location=location, deployment=deployment,
+ )
+ actual = GameServerDeploymentsServiceClient.game_server_deployment_rollout_path(
+ project, location, deployment
+ )
+ assert expected == actual
+
+
+def test_parse_game_server_deployment_rollout_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "deployment": "nudibranch",
+ }
+ path = GameServerDeploymentsServiceClient.game_server_deployment_rollout_path(
+ **expected
+ )
+
+ # Check that the path construction is reversible.
+ actual = GameServerDeploymentsServiceClient.parse_game_server_deployment_rollout_path(
+ path
+ )
+ assert expected == actual
diff --git a/tests/unit/gapic/gaming_v1/test_realms_service.py b/tests/unit/gapic/gaming_v1/test_realms_service.py
new file mode 100644
index 00000000..16ecfe32
--- /dev/null
+++ b/tests/unit/gapic/gaming_v1/test_realms_service.py
@@ -0,0 +1,1884 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import future
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.api_core import operation_async
+from google.api_core import operations_v1
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.gaming_v1.services.realms_service import RealmsServiceAsyncClient
+from google.cloud.gaming_v1.services.realms_service import RealmsServiceClient
+from google.cloud.gaming_v1.services.realms_service import pagers
+from google.cloud.gaming_v1.services.realms_service import transports
+from google.cloud.gaming_v1.types import common
+from google.cloud.gaming_v1.types import realms
+from google.longrunning import operations_pb2
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+def test__get_default_mtls_endpoint():
+ api_endpoint = "example.googleapis.com"
+ api_mtls_endpoint = "example.mtls.googleapis.com"
+ sandbox_endpoint = "example.sandbox.googleapis.com"
+ sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
+ non_googleapi = "api.example.com"
+
+ assert RealmsServiceClient._get_default_mtls_endpoint(None) is None
+ assert (
+ RealmsServiceClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ RealmsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ RealmsServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ RealmsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ RealmsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [RealmsServiceClient, RealmsServiceAsyncClient]
+)
+def test_realms_service_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_realms_service_client_get_transport_class():
+ transport = RealmsServiceClient.get_transport_class()
+ assert transport == transports.RealmsServiceGrpcTransport
+
+ transport = RealmsServiceClient.get_transport_class("grpc")
+ assert transport == transports.RealmsServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (RealmsServiceClient, transports.RealmsServiceGrpcTransport, "grpc"),
+ (
+ RealmsServiceAsyncClient,
+ transports.RealmsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_realms_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(RealmsServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(RealmsServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "never".
+ os.environ["GOOGLE_API_USE_MTLS"] = "never"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is
+ # "always".
+ os.environ["GOOGLE_API_USE_MTLS"] = "always"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=client_cert_source_callback,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", and default_client_cert_source is provided.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is
+ # "auto", but client_cert_source and default_client_cert_source are None.
+ os.environ["GOOGLE_API_USE_MTLS"] = "auto"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has
+ # unsupported value.
+ os.environ["GOOGLE_API_USE_MTLS"] = "Unsupported"
+ with pytest.raises(MutualTLSChannelError):
+ client = client_class()
+
+ del os.environ["GOOGLE_API_USE_MTLS"]
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (RealmsServiceClient, transports.RealmsServiceGrpcTransport, "grpc"),
+ (
+ RealmsServiceAsyncClient,
+ transports.RealmsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_realms_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=["1", "2"],
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (RealmsServiceClient, transports.RealmsServiceGrpcTransport, "grpc"),
+ (
+ RealmsServiceAsyncClient,
+ transports.RealmsServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_realms_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ api_mtls_endpoint=client.DEFAULT_ENDPOINT,
+ client_cert_source=None,
+ )
+
+
+def test_realms_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.gaming_v1.services.realms_service.transports.RealmsServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = RealmsServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ api_mtls_endpoint="squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+
+def test_list_realms(transport: str = "grpc"):
+ client = RealmsServiceClient(
+ credentials=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 = realms.ListRealmsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = realms.ListRealmsResponse(
+ next_page_token="next_page_token_value", unreachable=["unreachable_value"],
+ )
+
+ response = client.list_realms(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, pagers.ListRealmsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+@pytest.mark.asyncio
+async def test_list_realms_async(transport: str = "grpc_asyncio"):
+ client = RealmsServiceAsyncClient(
+ credentials=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 = realms.ListRealmsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_realms), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ realms.ListRealmsResponse(
+ next_page_token="next_page_token_value",
+ unreachable=["unreachable_value"],
+ )
+ )
+
+ response = await client.list_realms(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 response is the type that we expect.
+ assert isinstance(response, pagers.ListRealmsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+ assert response.unreachable == ["unreachable_value"]
+
+
+def test_list_realms_field_headers():
+ client = RealmsServiceClient(credentials=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 = realms.ListRealmsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
+ call.return_value = realms.ListRealmsResponse()
+
+ client.list_realms(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_realms_field_headers_async():
+ client = RealmsServiceAsyncClient(credentials=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 = realms.ListRealmsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_realms), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ realms.ListRealmsResponse()
+ )
+
+ await client.list_realms(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_realms_flattened():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = realms.ListRealmsResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_realms(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+def test_list_realms_flattened_error():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.list_realms(
+ realms.ListRealmsRequest(), parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_realms_flattened_async():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_realms), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = realms.ListRealmsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ realms.ListRealmsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_realms(parent="parent_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+
+@pytest.mark.asyncio
+async def test_list_realms_flattened_error_async():
+ client = RealmsServiceAsyncClient(credentials=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_realms(
+ realms.ListRealmsRequest(), parent="parent_value",
+ )
+
+
+def test_list_realms_pager():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ realms.ListRealmsResponse(
+ realms=[realms.Realm(), realms.Realm(), realms.Realm(),],
+ next_page_token="abc",
+ ),
+ realms.ListRealmsResponse(realms=[], next_page_token="def",),
+ realms.ListRealmsResponse(realms=[realms.Realm(),], next_page_token="ghi",),
+ realms.ListRealmsResponse(realms=[realms.Realm(), realms.Realm(),],),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_realms(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, realms.Realm) for i in results)
+
+
+def test_list_realms_pages():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.list_realms), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ realms.ListRealmsResponse(
+ realms=[realms.Realm(), realms.Realm(), realms.Realm(),],
+ next_page_token="abc",
+ ),
+ realms.ListRealmsResponse(realms=[], next_page_token="def",),
+ realms.ListRealmsResponse(realms=[realms.Realm(),], next_page_token="ghi",),
+ realms.ListRealmsResponse(realms=[realms.Realm(), realms.Realm(),],),
+ RuntimeError,
+ )
+ pages = list(client.list_realms(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_realms_async_pager():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_realms),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ realms.ListRealmsResponse(
+ realms=[realms.Realm(), realms.Realm(), realms.Realm(),],
+ next_page_token="abc",
+ ),
+ realms.ListRealmsResponse(realms=[], next_page_token="def",),
+ realms.ListRealmsResponse(realms=[realms.Realm(),], next_page_token="ghi",),
+ realms.ListRealmsResponse(realms=[realms.Realm(), realms.Realm(),],),
+ RuntimeError,
+ )
+ async_pager = await client.list_realms(request={},)
+ assert async_pager.next_page_token == "abc"
+ responses = []
+ async for response in async_pager:
+ responses.append(response)
+
+ assert len(responses) == 6
+ assert all(isinstance(i, realms.Realm) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_realms_async_pages():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_realms),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ realms.ListRealmsResponse(
+ realms=[realms.Realm(), realms.Realm(), realms.Realm(),],
+ next_page_token="abc",
+ ),
+ realms.ListRealmsResponse(realms=[], next_page_token="def",),
+ realms.ListRealmsResponse(realms=[realms.Realm(),], next_page_token="ghi",),
+ realms.ListRealmsResponse(realms=[realms.Realm(), realms.Realm(),],),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.list_realms(request={})).pages:
+ pages.append(page)
+ for page, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page.raw_page.next_page_token == token
+
+
+def test_get_realm(transport: str = "grpc"):
+ client = RealmsServiceClient(
+ credentials=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 = realms.GetRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.get_realm), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = realms.Realm(
+ name="name_value",
+ time_zone="time_zone_value",
+ etag="etag_value",
+ description="description_value",
+ )
+
+ response = client.get_realm(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, realms.Realm)
+
+ assert response.name == "name_value"
+
+ assert response.time_zone == "time_zone_value"
+
+ assert response.etag == "etag_value"
+
+ assert response.description == "description_value"
+
+
+@pytest.mark.asyncio
+async def test_get_realm_async(transport: str = "grpc_asyncio"):
+ client = RealmsServiceAsyncClient(
+ credentials=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 = realms.GetRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_realm), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ realms.Realm(
+ name="name_value",
+ time_zone="time_zone_value",
+ etag="etag_value",
+ description="description_value",
+ )
+ )
+
+ response = await client.get_realm(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 response is the type that we expect.
+ assert isinstance(response, realms.Realm)
+
+ assert response.name == "name_value"
+
+ assert response.time_zone == "time_zone_value"
+
+ assert response.etag == "etag_value"
+
+ assert response.description == "description_value"
+
+
+def test_get_realm_field_headers():
+ client = RealmsServiceClient(credentials=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 = realms.GetRealmRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.get_realm), "__call__") as call:
+ call.return_value = realms.Realm()
+
+ client.get_realm(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_realm_field_headers_async():
+ client = RealmsServiceAsyncClient(credentials=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 = realms.GetRealmRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_realm), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(realms.Realm())
+
+ await client.get_realm(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_realm_flattened():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.get_realm), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = realms.Realm()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_realm(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_get_realm_flattened_error():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_realm(
+ realms.GetRealmRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_realm_flattened_async():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_realm), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = realms.Realm()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(realms.Realm())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_realm(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_get_realm_flattened_error_async():
+ client = RealmsServiceAsyncClient(credentials=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_realm(
+ realms.GetRealmRequest(), name="name_value",
+ )
+
+
+def test_create_realm(transport: str = "grpc"):
+ client = RealmsServiceClient(
+ credentials=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 = realms.CreateRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.create_realm), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.create_realm(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_create_realm_async(transport: str = "grpc_asyncio"):
+ client = RealmsServiceAsyncClient(
+ credentials=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 = realms.CreateRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_realm), "__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_realm(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_create_realm_field_headers():
+ client = RealmsServiceClient(credentials=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 = realms.CreateRealmRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.create_realm), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.create_realm(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_realm_field_headers_async():
+ client = RealmsServiceAsyncClient(credentials=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 = realms.CreateRealmRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_realm), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.create_realm(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_realm_flattened():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.create_realm), "__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_realm(
+ parent="parent_value",
+ realm=realms.Realm(name="name_value"),
+ realm_id="realm_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]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].realm == realms.Realm(name="name_value")
+
+ assert args[0].realm_id == "realm_id_value"
+
+
+def test_create_realm_flattened_error():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.create_realm(
+ realms.CreateRealmRequest(),
+ parent="parent_value",
+ realm=realms.Realm(name="name_value"),
+ realm_id="realm_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_realm_flattened_async():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_realm), "__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_realm(
+ parent="parent_value",
+ realm=realms.Realm(name="name_value"),
+ realm_id="realm_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]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].realm == realms.Realm(name="name_value")
+
+ assert args[0].realm_id == "realm_id_value"
+
+
+@pytest.mark.asyncio
+async def test_create_realm_flattened_error_async():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.create_realm(
+ realms.CreateRealmRequest(),
+ parent="parent_value",
+ realm=realms.Realm(name="name_value"),
+ realm_id="realm_id_value",
+ )
+
+
+def test_delete_realm(transport: str = "grpc"):
+ client = RealmsServiceClient(
+ credentials=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 = realms.DeleteRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.delete_realm), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.delete_realm(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_delete_realm_async(transport: str = "grpc_asyncio"):
+ client = RealmsServiceAsyncClient(
+ credentials=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 = realms.DeleteRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_realm), "__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_realm(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_realm_field_headers():
+ client = RealmsServiceClient(credentials=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 = realms.DeleteRealmRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.delete_realm), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.delete_realm(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_realm_field_headers_async():
+ client = RealmsServiceAsyncClient(credentials=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 = realms.DeleteRealmRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_realm), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.delete_realm(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_realm_flattened():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.delete_realm), "__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_realm(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_delete_realm_flattened_error():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_realm(
+ realms.DeleteRealmRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_realm_flattened_async():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_realm), "__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_realm(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_delete_realm_flattened_error_async():
+ client = RealmsServiceAsyncClient(credentials=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_realm(
+ realms.DeleteRealmRequest(), name="name_value",
+ )
+
+
+def test_update_realm(transport: str = "grpc"):
+ client = RealmsServiceClient(
+ credentials=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 = realms.UpdateRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.update_realm), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+
+ response = client.update_realm(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, future.Future)
+
+
+@pytest.mark.asyncio
+async def test_update_realm_async(transport: str = "grpc_asyncio"):
+ client = RealmsServiceAsyncClient(
+ credentials=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 = realms.UpdateRealmRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_realm), "__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.update_realm(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 response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_update_realm_field_headers():
+ client = RealmsServiceClient(credentials=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 = realms.UpdateRealmRequest()
+ request.realm.name = "realm.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.update_realm), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+
+ client.update_realm(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", "realm.name=realm.name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_realm_field_headers_async():
+ client = RealmsServiceAsyncClient(credentials=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 = realms.UpdateRealmRequest()
+ request.realm.name = "realm.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_realm), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+
+ await client.update_realm(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", "realm.name=realm.name/value",) in kw["metadata"]
+
+
+def test_update_realm_flattened():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.update_realm), "__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.update_realm(
+ realm=realms.Realm(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].realm == realms.Realm(name="name_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_realm_flattened_error():
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_realm(
+ realms.UpdateRealmRequest(),
+ realm=realms.Realm(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_realm_flattened_async():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_realm), "__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.update_realm(
+ realm=realms.Realm(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].realm == realms.Realm(name="name_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_realm_flattened_error_async():
+ client = RealmsServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.update_realm(
+ realms.UpdateRealmRequest(),
+ realm=realms.Realm(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_preview_realm_update(transport: str = "grpc"):
+ client = RealmsServiceClient(
+ credentials=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 = realms.PreviewRealmUpdateRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_realm_update), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = realms.PreviewRealmUpdateResponse(etag="etag_value",)
+
+ response = client.preview_realm_update(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, realms.PreviewRealmUpdateResponse)
+
+ assert response.etag == "etag_value"
+
+
+@pytest.mark.asyncio
+async def test_preview_realm_update_async(transport: str = "grpc_asyncio"):
+ client = RealmsServiceAsyncClient(
+ credentials=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 = realms.PreviewRealmUpdateRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_realm_update), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ realms.PreviewRealmUpdateResponse(etag="etag_value",)
+ )
+
+ response = await client.preview_realm_update(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 response is the type that we expect.
+ assert isinstance(response, realms.PreviewRealmUpdateResponse)
+
+ assert response.etag == "etag_value"
+
+
+def test_preview_realm_update_field_headers():
+ client = RealmsServiceClient(credentials=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 = realms.PreviewRealmUpdateRequest()
+ request.realm.name = "realm.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.preview_realm_update), "__call__"
+ ) as call:
+ call.return_value = realms.PreviewRealmUpdateResponse()
+
+ client.preview_realm_update(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", "realm.name=realm.name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_preview_realm_update_field_headers_async():
+ client = RealmsServiceAsyncClient(credentials=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 = realms.PreviewRealmUpdateRequest()
+ request.realm.name = "realm.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.preview_realm_update), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ realms.PreviewRealmUpdateResponse()
+ )
+
+ await client.preview_realm_update(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", "realm.name=realm.name/value",) in kw["metadata"]
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.RealmsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = RealmsServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.RealmsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = RealmsServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.RealmsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = RealmsServiceClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.RealmsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = RealmsServiceClient(transport=transport)
+ assert client._transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.RealmsServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.RealmsServiceGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = RealmsServiceClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client._transport, transports.RealmsServiceGrpcTransport,)
+
+
+def test_realms_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.RealmsServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_realms_service_base_transport():
+ # Instantiate the base transport.
+ transport = transports.RealmsServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "list_realms",
+ "get_realm",
+ "create_realm",
+ "delete_realm",
+ "update_realm",
+ "preview_realm_update",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+
+def test_realms_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(auth, "load_credentials_from_file") as load_creds:
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.RealmsServiceTransport(
+ credentials_file="credentials.json",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ )
+
+
+def test_realms_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ RealmsServiceClient()
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_realms_service_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.RealmsServiceGrpcTransport(host="squid.clam.whelk")
+ adc.assert_called_once_with(
+ scopes=("https://www.googleapis.com/auth/cloud-platform",)
+ )
+
+
+def test_realms_service_host_no_port():
+ client = RealmsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:443"
+
+
+def test_realms_service_host_with_port():
+ client = RealmsServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="gameservices.googleapis.com:8000"
+ ),
+ )
+ assert client._transport._host == "gameservices.googleapis.com:8000"
+
+
+def test_realms_service_grpc_transport_channel():
+ channel = grpc.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.RealmsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+def test_realms_service_grpc_asyncio_transport_channel():
+ channel = aio.insecure_channel("http://localhost/")
+
+ # Check that if channel is provided, mtls endpoint and client_cert_source
+ # won't be used.
+ callback = mock.MagicMock()
+ transport = transports.RealmsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=callback,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert not callback.called
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_realms_service_grpc_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.RealmsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@mock.patch("grpc.ssl_channel_credentials", autospec=True)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_realms_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source(
+ grpc_create_channel, grpc_ssl_channel_cred
+):
+ # Check that if channel is None, but api_mtls_endpoint and client_cert_source
+ # are provided, then a mTLS channel will be created.
+ mock_cred = mock.Mock()
+
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ transport = transports.RealmsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
+def test_realms_service_grpc_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.RealmsServiceGrpcTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
+)
+@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True)
+def test_realms_service_grpc_asyncio_transport_channel_mtls_with_adc(
+ grpc_create_channel, api_mtls_endpoint
+):
+ # Check that if channel and client_cert_source are None, but api_mtls_endpoint
+ # is provided, then a mTLS channel will be created with SSL ADC.
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ # Mock google.auth.transport.grpc.SslCredentials class.
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ mock_cred = mock.Mock()
+ transport = transports.RealmsServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint=api_mtls_endpoint,
+ client_cert_source=None,
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ ssl_credentials=mock_ssl_cred,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_realms_service_grpc_lro_client():
+ client = RealmsServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc",
+ )
+ transport = client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_realms_service_grpc_lro_async_client():
+ client = RealmsServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ )
+ transport = client._client._transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,)
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_realm_path():
+ project = "squid"
+ location = "clam"
+ realm = "whelk"
+
+ expected = "projects/{project}/locations/{location}/realms/{realm}".format(
+ project=project, location=location, realm=realm,
+ )
+ actual = RealmsServiceClient.realm_path(project, location, realm)
+ assert expected == actual
+
+
+def test_parse_realm_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "realm": "nudibranch",
+ }
+ path = RealmsServiceClient.realm_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = RealmsServiceClient.parse_realm_path(path)
+ assert expected == actual