diff --git a/.gitignore b/.gitignore index b87e1ed5..b9daa52f 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,7 @@ pip-log.txt # Built documentation docs/_build bigquery/docs/generated +docs.metadata # Virtual environment env/ @@ -57,4 +58,4 @@ system_tests/local_test_setup # Make sure a generated file isn't accidentally committed. pylintrc -pylintrc.test \ No newline at end of file +pylintrc.test diff --git a/.kokoro/build.sh b/.kokoro/build.sh index 113340da..5d03ac70 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -36,4 +36,10 @@ python3.6 -m pip uninstall --yes --quiet nox-automation python3.6 -m pip install --upgrade --quiet nox python3.6 -m nox --version -python3.6 -m nox +# If NOX_SESSION is set, it only runs the specified session, +# otherwise run all the sessions. +if [[ -n "${NOX_SESSION:-}" ]]; then + python3.6 -m nox -s "${NOX_SESSION:-}" +else + python3.6 -m nox +fi diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile new file mode 100644 index 00000000..412b0b56 --- /dev/null +++ b/.kokoro/docker/docs/Dockerfile @@ -0,0 +1,98 @@ +# 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 ubuntu:20.04 + +ENV DEBIAN_FRONTEND noninteractive + +# Ensure local Python is preferred over distribution Python. +ENV PATH /usr/local/bin:$PATH + +# Install dependencies. +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + apt-transport-https \ + build-essential \ + ca-certificates \ + curl \ + dirmngr \ + git \ + gpg-agent \ + graphviz \ + libbz2-dev \ + libdb5.3-dev \ + libexpat1-dev \ + libffi-dev \ + liblzma-dev \ + libreadline-dev \ + libsnappy-dev \ + libssl-dev \ + libsqlite3-dev \ + portaudio19-dev \ + redis-server \ + software-properties-common \ + ssh \ + sudo \ + tcl \ + tcl-dev \ + tk \ + tk-dev \ + uuid-dev \ + wget \ + zlib1g-dev \ + && add-apt-repository universe \ + && apt-get update \ + && apt-get -y install jq \ + && apt-get clean autoclean \ + && apt-get autoremove -y \ + && rm -rf /var/lib/apt/lists/* \ + && rm -f /var/cache/apt/archives/*.deb + + +COPY fetch_gpg_keys.sh /tmp +# Install the desired versions of Python. +RUN set -ex \ + && export GNUPGHOME="$(mktemp -d)" \ + && echo "disable-ipv6" >> "${GNUPGHOME}/dirmngr.conf" \ + && /tmp/fetch_gpg_keys.sh \ + && for PYTHON_VERSION in 3.7.8 3.8.5; do \ + wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \ + && wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \ + && gpg --batch --verify python-${PYTHON_VERSION}.tar.xz.asc python-${PYTHON_VERSION}.tar.xz \ + && rm -r python-${PYTHON_VERSION}.tar.xz.asc \ + && mkdir -p /usr/src/python-${PYTHON_VERSION} \ + && tar -xJC /usr/src/python-${PYTHON_VERSION} --strip-components=1 -f python-${PYTHON_VERSION}.tar.xz \ + && rm python-${PYTHON_VERSION}.tar.xz \ + && cd /usr/src/python-${PYTHON_VERSION} \ + && ./configure \ + --enable-shared \ + # This works only on Python 2.7 and throws a warning on every other + # version, but seems otherwise harmless. + --enable-unicode=ucs4 \ + --with-system-ffi \ + --without-ensurepip \ + && make -j$(nproc) \ + && make install \ + && ldconfig \ + ; done \ + && rm -rf "${GNUPGHOME}" \ + && rm -rf /usr/src/python* \ + && rm -rf ~/.cache/ + +RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ + && python3.7 /tmp/get-pip.py \ + && python3.8 /tmp/get-pip.py \ + && rm /tmp/get-pip.py + +CMD ["python3.7"] diff --git a/.kokoro/docker/docs/fetch_gpg_keys.sh b/.kokoro/docker/docs/fetch_gpg_keys.sh new file mode 100755 index 00000000..d653dd86 --- /dev/null +++ b/.kokoro/docker/docs/fetch_gpg_keys.sh @@ -0,0 +1,45 @@ +#!/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 +# +# 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. + +# A script to fetch gpg keys with retry. +# Avoid jinja parsing the file. +# + +function retry { + if [[ "${#}" -le 1 ]]; then + echo "Usage: ${0} retry_count commands.." + exit 1 + fi + local retries=${1} + local command="${@:2}" + until [[ "${retries}" -le 0 ]]; do + $command && return 0 + if [[ $? -ne 0 ]]; then + echo "command failed, retrying" + ((retries--)) + fi + done + return 1 +} + +# 3.6.9, 3.7.5 (Ned Deily) +retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ + 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D + +# 3.8.0 (Ɓukasz Langa) +retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ + E3FF2839C048B25C084DEBE9B26995E310250568 + +# diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 2f4f7220..d766113d 100644 --- a/.kokoro/docs/common.cfg +++ b/.kokoro/docs/common.cfg @@ -11,12 +11,12 @@ action { gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-game-servers/.kokoro/trampoline.sh" +build_file: "python-game-servers/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-multi" + value: "gcr.io/cloud-devrel-kokoro-resources/python-lib-docs" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" @@ -28,6 +28,23 @@ env_vars: { value: "docs-staging" } +env_vars: { + key: "V2_STAGING_BUCKET" + value: "docs-staging-v2-staging" +} + +# It will upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} + +# It will always build the docker image. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/docs/Dockerfile" +} + # Fetch the token needed for reporting release status to GitHub before_action { fetch_keystore { diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg new file mode 100644 index 00000000..11181078 --- /dev/null +++ b/.kokoro/docs/docs-presubmit.cfg @@ -0,0 +1,17 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "STAGING_BUCKET" + value: "gcloud-python-test" +} + +env_vars: { + key: "V2_STAGING_BUCKET" + value: "gcloud-python-test" +} + +# We only upload the image in the main `docs` build. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "false" +} diff --git a/.kokoro/publish-docs.sh b/.kokoro/publish-docs.sh index 456526bf..8acb14e8 100755 --- a/.kokoro/publish-docs.sh +++ b/.kokoro/publish-docs.sh @@ -18,26 +18,16 @@ set -eo pipefail # Disable buffering, so that the logs stream through. export PYTHONUNBUFFERED=1 -cd github/python-game-servers - -# Remove old nox -python3.6 -m pip uninstall --yes --quiet nox-automation +export PATH="${HOME}/.local/bin:${PATH}" # Install nox -python3.6 -m pip install --upgrade --quiet nox -python3.6 -m nox --version +python3 -m pip install --user --upgrade --quiet nox +python3 -m nox --version # build docs nox -s docs -python3 -m pip install gcp-docuploader - -# install a json parser -sudo apt-get update -sudo apt-get -y install software-properties-common -sudo add-apt-repository universe -sudo apt-get update -sudo apt-get -y install jq +python3 -m pip install --user gcp-docuploader # create metadata python3 -m docuploader create-metadata \ @@ -52,4 +42,23 @@ python3 -m docuploader create-metadata \ cat docs.metadata # upload docs -python3 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket docs-staging +python3 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket "${STAGING_BUCKET}" + + +# docfx yaml files +nox -s docfx + +# create metadata. +python3 -m docuploader create-metadata \ + --name=$(jq --raw-output '.name // empty' .repo-metadata.json) \ + --version=$(python3 setup.py --version) \ + --language=$(jq --raw-output '.language // empty' .repo-metadata.json) \ + --distribution-name=$(python3 setup.py --name) \ + --product-page=$(jq --raw-output '.product_documentation // empty' .repo-metadata.json) \ + --github-repository=$(jq --raw-output '.repo // empty' .repo-metadata.json) \ + --issue-tracker=$(jq --raw-output '.issue_tracker // empty' .repo-metadata.json) + +cat docs.metadata + +# upload docs +python3 -m docuploader upload docs/_build/html/docfx_yaml --metadata-file docs.metadata --destination-prefix docfx --staging-bucket "${V2_STAGING_BUCKET}" diff --git a/.kokoro/trampoline_v2.sh b/.kokoro/trampoline_v2.sh new file mode 100755 index 00000000..719bcd5b --- /dev/null +++ b/.kokoro/trampoline_v2.sh @@ -0,0 +1,487 @@ +#!/usr/bin/env 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 +# +# 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. + +# trampoline_v2.sh +# +# This script does 3 things. +# +# 1. Prepare the Docker image for the test +# 2. Run the Docker with appropriate flags to run the test +# 3. Upload the newly built Docker image +# +# in a way that is somewhat compatible with trampoline_v1. +# +# To run this script, first download few files from gcs to /dev/shm. +# (/dev/shm is passed into the container as KOKORO_GFILE_DIR). +# +# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/secrets_viewer_service_account.json /dev/shm +# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/automl_secrets.txt /dev/shm +# +# Then run the script. +# .kokoro/trampoline_v2.sh +# +# These environment variables are required: +# TRAMPOLINE_IMAGE: The docker image to use. +# TRAMPOLINE_DOCKERFILE: The location of the Dockerfile. +# +# You can optionally change these environment variables: +# TRAMPOLINE_IMAGE_UPLOAD: +# (true|false): Whether to upload the Docker image after the +# successful builds. +# TRAMPOLINE_BUILD_FILE: The script to run in the docker container. +# TRAMPOLINE_WORKSPACE: The workspace path in the docker container. +# Defaults to /workspace. +# Potentially there are some repo specific envvars in .trampolinerc in +# the project root. + + +set -euo pipefail + +TRAMPOLINE_VERSION="2.0.5" + +if command -v tput >/dev/null && [[ -n "${TERM:-}" ]]; then + readonly IO_COLOR_RED="$(tput setaf 1)" + readonly IO_COLOR_GREEN="$(tput setaf 2)" + readonly IO_COLOR_YELLOW="$(tput setaf 3)" + readonly IO_COLOR_RESET="$(tput sgr0)" +else + readonly IO_COLOR_RED="" + readonly IO_COLOR_GREEN="" + readonly IO_COLOR_YELLOW="" + readonly IO_COLOR_RESET="" +fi + +function function_exists { + [ $(LC_ALL=C type -t $1)"" == "function" ] +} + +# Logs a message using the given color. The first argument must be one +# of the IO_COLOR_* variables defined above, such as +# "${IO_COLOR_YELLOW}". The remaining arguments will be logged in the +# given color. The log message will also have an RFC-3339 timestamp +# prepended (in UTC). You can disable the color output by setting +# TERM=vt100. +function log_impl() { + local color="$1" + shift + local timestamp="$(date -u "+%Y-%m-%dT%H:%M:%SZ")" + echo "================================================================" + echo "${color}${timestamp}:" "$@" "${IO_COLOR_RESET}" + echo "================================================================" +} + +# Logs the given message with normal coloring and a timestamp. +function log() { + log_impl "${IO_COLOR_RESET}" "$@" +} + +# Logs the given message in green with a timestamp. +function log_green() { + log_impl "${IO_COLOR_GREEN}" "$@" +} + +# Logs the given message in yellow with a timestamp. +function log_yellow() { + log_impl "${IO_COLOR_YELLOW}" "$@" +} + +# Logs the given message in red with a timestamp. +function log_red() { + log_impl "${IO_COLOR_RED}" "$@" +} + +readonly tmpdir=$(mktemp -d -t ci-XXXXXXXX) +readonly tmphome="${tmpdir}/h" +mkdir -p "${tmphome}" + +function cleanup() { + rm -rf "${tmpdir}" +} +trap cleanup EXIT + +RUNNING_IN_CI="${RUNNING_IN_CI:-false}" + +# The workspace in the container, defaults to /workspace. +TRAMPOLINE_WORKSPACE="${TRAMPOLINE_WORKSPACE:-/workspace}" + +pass_down_envvars=( + # TRAMPOLINE_V2 variables. + # Tells scripts whether they are running as part of CI or not. + "RUNNING_IN_CI" + # Indicates which CI system we're in. + "TRAMPOLINE_CI" + # Indicates the version of the script. + "TRAMPOLINE_VERSION" +) + +log_yellow "Building with Trampoline ${TRAMPOLINE_VERSION}" + +# Detect which CI systems we're in. If we're in any of the CI systems +# we support, `RUNNING_IN_CI` will be true and `TRAMPOLINE_CI` will be +# the name of the CI system. Both envvars will be passing down to the +# container for telling which CI system we're in. +if [[ -n "${KOKORO_BUILD_ID:-}" ]]; then + # descriptive env var for indicating it's on CI. + RUNNING_IN_CI="true" + TRAMPOLINE_CI="kokoro" + if [[ "${TRAMPOLINE_USE_LEGACY_SERVICE_ACCOUNT:-}" == "true" ]]; then + if [[ ! -f "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" ]]; then + log_red "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json does not exist. Did you forget to mount cloud-devrel-kokoro-resources/trampoline? Aborting." + exit 1 + fi + # This service account will be activated later. + TRAMPOLINE_SERVICE_ACCOUNT="${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" + else + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + gcloud auth list + fi + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet + fi + pass_down_envvars+=( + # KOKORO dynamic variables. + "KOKORO_BUILD_NUMBER" + "KOKORO_BUILD_ID" + "KOKORO_JOB_NAME" + "KOKORO_GIT_COMMIT" + "KOKORO_GITHUB_COMMIT" + "KOKORO_GITHUB_PULL_REQUEST_NUMBER" + "KOKORO_GITHUB_PULL_REQUEST_COMMIT" + # For Build Cop Bot + "KOKORO_GITHUB_COMMIT_URL" + "KOKORO_GITHUB_PULL_REQUEST_URL" + ) +elif [[ "${TRAVIS:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="travis" + pass_down_envvars+=( + "TRAVIS_BRANCH" + "TRAVIS_BUILD_ID" + "TRAVIS_BUILD_NUMBER" + "TRAVIS_BUILD_WEB_URL" + "TRAVIS_COMMIT" + "TRAVIS_COMMIT_MESSAGE" + "TRAVIS_COMMIT_RANGE" + "TRAVIS_JOB_NAME" + "TRAVIS_JOB_NUMBER" + "TRAVIS_JOB_WEB_URL" + "TRAVIS_PULL_REQUEST" + "TRAVIS_PULL_REQUEST_BRANCH" + "TRAVIS_PULL_REQUEST_SHA" + "TRAVIS_PULL_REQUEST_SLUG" + "TRAVIS_REPO_SLUG" + "TRAVIS_SECURE_ENV_VARS" + "TRAVIS_TAG" + ) +elif [[ -n "${GITHUB_RUN_ID:-}" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="github-workflow" + pass_down_envvars+=( + "GITHUB_WORKFLOW" + "GITHUB_RUN_ID" + "GITHUB_RUN_NUMBER" + "GITHUB_ACTION" + "GITHUB_ACTIONS" + "GITHUB_ACTOR" + "GITHUB_REPOSITORY" + "GITHUB_EVENT_NAME" + "GITHUB_EVENT_PATH" + "GITHUB_SHA" + "GITHUB_REF" + "GITHUB_HEAD_REF" + "GITHUB_BASE_REF" + ) +elif [[ "${CIRCLECI:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="circleci" + pass_down_envvars+=( + "CIRCLE_BRANCH" + "CIRCLE_BUILD_NUM" + "CIRCLE_BUILD_URL" + "CIRCLE_COMPARE_URL" + "CIRCLE_JOB" + "CIRCLE_NODE_INDEX" + "CIRCLE_NODE_TOTAL" + "CIRCLE_PREVIOUS_BUILD_NUM" + "CIRCLE_PROJECT_REPONAME" + "CIRCLE_PROJECT_USERNAME" + "CIRCLE_REPOSITORY_URL" + "CIRCLE_SHA1" + "CIRCLE_STAGE" + "CIRCLE_USERNAME" + "CIRCLE_WORKFLOW_ID" + "CIRCLE_WORKFLOW_JOB_ID" + "CIRCLE_WORKFLOW_UPSTREAM_JOB_IDS" + "CIRCLE_WORKFLOW_WORKSPACE_ID" + ) +fi + +# Configure the service account for pulling the docker image. +function repo_root() { + local dir="$1" + while [[ ! -d "${dir}/.git" ]]; do + dir="$(dirname "$dir")" + done + echo "${dir}" +} + +# Detect the project root. In CI builds, we assume the script is in +# the git tree and traverse from there, otherwise, traverse from `pwd` +# to find `.git` directory. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + PROGRAM_PATH="$(realpath "$0")" + PROGRAM_DIR="$(dirname "${PROGRAM_PATH}")" + PROJECT_ROOT="$(repo_root "${PROGRAM_DIR}")" +else + PROJECT_ROOT="$(repo_root $(pwd))" +fi + +log_yellow "Changing to the project root: ${PROJECT_ROOT}." +cd "${PROJECT_ROOT}" + +# To support relative path for `TRAMPOLINE_SERVICE_ACCOUNT`, we need +# to use this environment variable in `PROJECT_ROOT`. +if [[ -n "${TRAMPOLINE_SERVICE_ACCOUNT:-}" ]]; then + + mkdir -p "${tmpdir}/gcloud" + gcloud_config_dir="${tmpdir}/gcloud" + + log_yellow "Using isolated gcloud config: ${gcloud_config_dir}." + export CLOUDSDK_CONFIG="${gcloud_config_dir}" + + log_yellow "Using ${TRAMPOLINE_SERVICE_ACCOUNT} for authentication." + gcloud auth activate-service-account \ + --key-file "${TRAMPOLINE_SERVICE_ACCOUNT}" + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet +fi + +required_envvars=( + # The basic trampoline configurations. + "TRAMPOLINE_IMAGE" + "TRAMPOLINE_BUILD_FILE" +) + +if [[ -f "${PROJECT_ROOT}/.trampolinerc" ]]; then + source "${PROJECT_ROOT}/.trampolinerc" +fi + +log_yellow "Checking environment variables." +for e in "${required_envvars[@]}" +do + if [[ -z "${!e:-}" ]]; then + log "Missing ${e} env var. Aborting." + exit 1 + fi +done + +# We want to support legacy style TRAMPOLINE_BUILD_FILE used with V1 +# script: e.g. "github/repo-name/.kokoro/run_tests.sh" +TRAMPOLINE_BUILD_FILE="${TRAMPOLINE_BUILD_FILE#github/*/}" +log_yellow "Using TRAMPOLINE_BUILD_FILE: ${TRAMPOLINE_BUILD_FILE}" + +# ignore error on docker operations and test execution +set +e + +log_yellow "Preparing Docker image." +# We only download the docker image in CI builds. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + # Download the docker image specified by `TRAMPOLINE_IMAGE` + + # We may want to add --max-concurrent-downloads flag. + + log_yellow "Start pulling the Docker image: ${TRAMPOLINE_IMAGE}." + if docker pull "${TRAMPOLINE_IMAGE}"; then + log_green "Finished pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="true" + else + log_red "Failed pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="false" + fi +else + # For local run, check if we have the image. + if docker images "${TRAMPOLINE_IMAGE}:latest" | grep "${TRAMPOLINE_IMAGE}"; then + has_image="true" + else + has_image="false" + fi +fi + + +# The default user for a Docker container has uid 0 (root). To avoid +# creating root-owned files in the build directory we tell docker to +# use the current user ID. +user_uid="$(id -u)" +user_gid="$(id -g)" +user_name="$(id -un)" + +# To allow docker in docker, we add the user to the docker group in +# the host os. +docker_gid=$(cut -d: -f3 < <(getent group docker)) + +update_cache="false" +if [[ "${TRAMPOLINE_DOCKERFILE:-none}" != "none" ]]; then + # Build the Docker image from the source. + context_dir=$(dirname "${TRAMPOLINE_DOCKERFILE}") + docker_build_flags=( + "-f" "${TRAMPOLINE_DOCKERFILE}" + "-t" "${TRAMPOLINE_IMAGE}" + "--build-arg" "UID=${user_uid}" + "--build-arg" "USERNAME=${user_name}" + ) + if [[ "${has_image}" == "true" ]]; then + docker_build_flags+=("--cache-from" "${TRAMPOLINE_IMAGE}") + fi + + log_yellow "Start building the docker image." + if [[ "${TRAMPOLINE_VERBOSE:-false}" == "true" ]]; then + echo "docker build" "${docker_build_flags[@]}" "${context_dir}" + fi + + # ON CI systems, we want to suppress docker build logs, only + # output the logs when it fails. + if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + if docker build "${docker_build_flags[@]}" "${context_dir}" \ + > "${tmpdir}/docker_build.log" 2>&1; then + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + cat "${tmpdir}/docker_build.log" + fi + + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + log_yellow "Dumping the build logs:" + cat "${tmpdir}/docker_build.log" + exit 1 + fi + else + if docker build "${docker_build_flags[@]}" "${context_dir}"; then + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + exit 1 + fi + fi +else + if [[ "${has_image}" != "true" ]]; then + log_red "We do not have ${TRAMPOLINE_IMAGE} locally, aborting." + exit 1 + fi +fi + +# We use an array for the flags so they are easier to document. +docker_flags=( + # Remove the container after it exists. + "--rm" + + # Use the host network. + "--network=host" + + # Run in priviledged mode. We are not using docker for sandboxing or + # isolation, just for packaging our dev tools. + "--privileged" + + # Run the docker script with the user id. Because the docker image gets to + # write in ${PWD} you typically want this to be your user id. + # To allow docker in docker, we need to use docker gid on the host. + "--user" "${user_uid}:${docker_gid}" + + # Pass down the USER. + "--env" "USER=${user_name}" + + # Mount the project directory inside the Docker container. + "--volume" "${PROJECT_ROOT}:${TRAMPOLINE_WORKSPACE}" + "--workdir" "${TRAMPOLINE_WORKSPACE}" + "--env" "PROJECT_ROOT=${TRAMPOLINE_WORKSPACE}" + + # Mount the temporary home directory. + "--volume" "${tmphome}:/h" + "--env" "HOME=/h" + + # Allow docker in docker. + "--volume" "/var/run/docker.sock:/var/run/docker.sock" + + # Mount the /tmp so that docker in docker can mount the files + # there correctly. + "--volume" "/tmp:/tmp" + # Pass down the KOKORO_GFILE_DIR and KOKORO_KEYSTORE_DIR + # TODO(tmatsuo): This part is not portable. + "--env" "TRAMPOLINE_SECRET_DIR=/secrets" + "--volume" "${KOKORO_GFILE_DIR:-/dev/shm}:/secrets/gfile" + "--env" "KOKORO_GFILE_DIR=/secrets/gfile" + "--volume" "${KOKORO_KEYSTORE_DIR:-/dev/shm}:/secrets/keystore" + "--env" "KOKORO_KEYSTORE_DIR=/secrets/keystore" +) + +# Add an option for nicer output if the build gets a tty. +if [[ -t 0 ]]; then + docker_flags+=("-it") +fi + +# Passing down env vars +for e in "${pass_down_envvars[@]}" +do + if [[ -n "${!e:-}" ]]; then + docker_flags+=("--env" "${e}=${!e}") + fi +done + +# If arguments are given, all arguments will become the commands run +# in the container, otherwise run TRAMPOLINE_BUILD_FILE. +if [[ $# -ge 1 ]]; then + log_yellow "Running the given commands '" "${@:1}" "' in the container." + readonly commands=("${@:1}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" +else + log_yellow "Running the tests in a Docker container." + docker_flags+=("--entrypoint=${TRAMPOLINE_BUILD_FILE}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" +fi + + +test_retval=$? + +if [[ ${test_retval} -eq 0 ]]; then + log_green "Build finished with ${test_retval}" +else + log_red "Build finished with ${test_retval}" +fi + +# Only upload it when the test passes. +if [[ "${update_cache}" == "true" ]] && \ + [[ $test_retval == 0 ]] && \ + [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]]; then + log_yellow "Uploading the Docker image." + if docker push "${TRAMPOLINE_IMAGE}"; then + log_green "Finished uploading the Docker image." + else + log_red "Failed uploading the Docker image." + fi + # Call trampoline_after_upload_hook if it's defined. + if function_exists trampoline_after_upload_hook; then + trampoline_after_upload_hook + fi + +fi + +exit "${test_retval}" diff --git a/.trampolinerc b/.trampolinerc new file mode 100644 index 00000000..995ee291 --- /dev/null +++ b/.trampolinerc @@ -0,0 +1,51 @@ +# 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. + +# Template for .trampolinerc + +# Add required env vars here. +required_envvars+=( + "STAGING_BUCKET" + "V2_STAGING_BUCKET" +) + +# Add env vars which are passed down into the container here. +pass_down_envvars+=( + "STAGING_BUCKET" + "V2_STAGING_BUCKET" +) + +# Prevent unintentional override on the default image. +if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \ + [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image." + exit 1 +fi + +# Define the default value if it makes sense. +if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then + TRAMPOLINE_IMAGE_UPLOAD="" +fi + +if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + TRAMPOLINE_IMAGE="" +fi + +if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then + TRAMPOLINE_DOCKERFILE="" +fi + +if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then + TRAMPOLINE_BUILD_FILE="" +fi diff --git a/docs/conf.py b/docs/conf.py index cf544790..83681ccb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,6 +20,10 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ @@ -90,7 +94,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. diff --git a/docs/gaming_v1beta/services.rst b/docs/gaming_v1beta/services.rst new file mode 100644 index 00000000..70c98979 --- /dev/null +++ b/docs/gaming_v1beta/services.rst @@ -0,0 +1,15 @@ +Services for Google Cloud Gaming v1beta API +=========================================== + +.. automodule:: google.cloud.gaming_v1beta.services.game_server_clusters_service + :members: + :inherited-members: +.. automodule:: google.cloud.gaming_v1beta.services.game_server_configs_service + :members: + :inherited-members: +.. automodule:: google.cloud.gaming_v1beta.services.game_server_deployments_service + :members: + :inherited-members: +.. automodule:: google.cloud.gaming_v1beta.services.realms_service + :members: + :inherited-members: diff --git a/docs/gaming_v1beta/types.rst b/docs/gaming_v1beta/types.rst new file mode 100644 index 00000000..da332a14 --- /dev/null +++ b/docs/gaming_v1beta/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Gaming v1beta API +======================================== + +.. automodule:: google.cloud.gaming_v1beta.types + :members: diff --git a/docs/index.rst b/docs/index.rst index b0cced1f..625f70ee 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -2,7 +2,7 @@ .. include:: multiprocessing.rst -API Reference +v1 Reference ------------- .. toctree:: :maxdepth: 2 @@ -10,6 +10,14 @@ API Reference gaming_v1/services gaming_v1/types +v1beta Reference +---------------- +.. toctree:: + :maxdepth: 2 + + gaming_v1beta/services + gaming_v1beta/types + Changelog --------- diff --git a/gaming-v1beta-py.tar.gz b/gaming-v1beta-py.tar.gz new file mode 100644 index 00000000..e69de29b diff --git a/google/cloud/gaming_v1/__init__.py b/google/cloud/gaming_v1/__init__.py index 360278e0..cddeaeec 100644 --- a/google/cloud/gaming_v1/__init__.py +++ b/google/cloud/gaming_v1/__init__.py @@ -98,6 +98,7 @@ "GameServerConfigsServiceClient", "GameServerDeployment", "GameServerDeploymentRollout", + "GameServerDeploymentsServiceClient", "GetGameServerClusterRequest", "GetGameServerConfigRequest", "GetGameServerDeploymentRequest", @@ -127,7 +128,6 @@ "PreviewUpdateGameServerClusterResponse", "Realm", "RealmSelector", - "RealmsServiceClient", "ScalingConfig", "Schedule", "SpecSource", @@ -137,5 +137,5 @@ "UpdateGameServerDeploymentRequest", "UpdateGameServerDeploymentRolloutRequest", "UpdateRealmRequest", - "GameServerDeploymentsServiceClient", + "RealmsServiceClient", ) 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 index dd014a19..124176f2 100644 --- 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 @@ -167,7 +167,13 @@ async def list_game_server_clusters( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_game_server_clusters, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -244,7 +250,13 @@ async def get_game_server_cluster( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_game_server_cluster, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -339,7 +351,7 @@ async def create_game_server_cluster( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.create_game_server_cluster, - default_timeout=None, + default_timeout=120.0, client_info=_client_info, ) @@ -399,7 +411,13 @@ async def preview_create_game_server_cluster( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.preview_create_game_server_cluster, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -486,7 +504,7 @@ async def delete_game_server_cluster( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_game_server_cluster, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -545,7 +563,13 @@ async def preview_delete_game_server_cluster( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.preview_delete_game_server_cluster, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -632,7 +656,7 @@ async def update_game_server_cluster( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_game_server_cluster, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -693,7 +717,13 @@ async def preview_update_game_server_cluster( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.preview_update_game_server_cluster, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) 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 941dbd25..608f482e 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 @@ -243,6 +243,7 @@ def __init__( scopes=client_options.scopes, api_mtls_endpoint=client_options.api_endpoint, client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, ) def list_game_server_clusters( @@ -287,27 +288,31 @@ def list_game_server_clusters( # 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]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_clusters.ListGameServerClustersRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.ListGameServerClustersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.ListGameServerClustersRequest): + request = game_server_clusters.ListGameServerClustersRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + 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.wrap_method( - self._transport.list_game_server_clusters, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.list_game_server_clusters + ] # Certain fields should be provided within the metadata header; # add these here. @@ -364,27 +369,29 @@ def get_game_server_cluster( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_clusters.GetGameServerClusterRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.GetGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.GetGameServerClusterRequest): + request = game_server_clusters.GetGameServerClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.get_game_server_cluster, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_game_server_cluster] # Certain fields should be provided within the metadata header; # add these here. @@ -453,33 +460,37 @@ def create_game_server_cluster( # 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( + has_flattened_params = any( [parent, game_server_cluster, game_server_cluster_id] - ): + ) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_clusters.CreateGameServerClusterRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.CreateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.CreateGameServerClusterRequest): + request = game_server_clusters.CreateGameServerClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.create_game_server_cluster, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.create_game_server_cluster + ] # Certain fields should be provided within the metadata header; # add these here. @@ -531,15 +542,22 @@ def preview_create_game_server_cluster( """ # Create or coerce a protobuf request object. - request = game_server_clusters.PreviewCreateGameServerClusterRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.PreviewCreateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_clusters.PreviewCreateGameServerClusterRequest + ): + request = game_server_clusters.PreviewCreateGameServerClusterRequest( + request + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.preview_create_game_server_cluster, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.preview_create_game_server_cluster + ] # Certain fields should be provided within the metadata header; # add these here. @@ -606,27 +624,31 @@ def delete_game_server_cluster( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_clusters.DeleteGameServerClusterRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.DeleteGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.DeleteGameServerClusterRequest): + request = game_server_clusters.DeleteGameServerClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.delete_game_server_cluster, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.delete_game_server_cluster + ] # Certain fields should be provided within the metadata header; # add these here. @@ -677,15 +699,22 @@ def preview_delete_game_server_cluster( """ # Create or coerce a protobuf request object. - request = game_server_clusters.PreviewDeleteGameServerClusterRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.PreviewDeleteGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_clusters.PreviewDeleteGameServerClusterRequest + ): + request = game_server_clusters.PreviewDeleteGameServerClusterRequest( + request + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.preview_delete_game_server_cluster, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.preview_delete_game_server_cluster + ] # Certain fields should be provided within the metadata header; # add these here. @@ -750,29 +779,33 @@ def update_game_server_cluster( # 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]): + has_flattened_params = any([game_server_cluster, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_clusters.UpdateGameServerClusterRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.UpdateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.UpdateGameServerClusterRequest): + request = game_server_clusters.UpdateGameServerClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.update_game_server_cluster, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_game_server_cluster + ] # Certain fields should be provided within the metadata header; # add these here. @@ -825,15 +858,22 @@ def preview_update_game_server_cluster( """ # Create or coerce a protobuf request object. - request = game_server_clusters.PreviewUpdateGameServerClusterRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.PreviewUpdateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_clusters.PreviewUpdateGameServerClusterRequest + ): + request = game_server_clusters.PreviewUpdateGameServerClusterRequest( + request + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.preview_update_game_server_cluster, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.preview_update_game_server_cluster + ] # Certain fields should be provided within the metadata header; # add these here. 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 6da4c579..c8716436 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 @@ -17,9 +17,12 @@ import abc import typing +import pkg_resources from google import auth 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.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -27,6 +30,16 @@ from google.longrunning import operations_pb2 as operations # type: ignore +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() + + class GameServerClustersServiceTransport(abc.ABC): """Abstract transport class for GameServerClustersService.""" @@ -39,6 +52,7 @@ def __init__( credentials: credentials.Credentials = None, credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -54,6 +68,8 @@ def __init__( 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -69,14 +85,95 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes + credentials_file, scopes=scopes, quota_project_id=quota_project_id ) + elif credentials is None: - credentials, _ = auth.default(scopes=scopes) + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_game_server_clusters: gapic_v1.method.wrap_method( + self.list_game_server_clusters, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_cluster: gapic_v1.method.wrap_method( + self.get_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_game_server_cluster: gapic_v1.method.wrap_method( + self.create_game_server_cluster, + default_timeout=120.0, + client_info=_client_info, + ), + self.preview_create_game_server_cluster: gapic_v1.method.wrap_method( + self.preview_create_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_game_server_cluster: gapic_v1.method.wrap_method( + self.delete_game_server_cluster, + default_timeout=60.0, + client_info=_client_info, + ), + self.preview_delete_game_server_cluster: gapic_v1.method.wrap_method( + self.preview_delete_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_game_server_cluster: gapic_v1.method.wrap_method( + self.update_game_server_cluster, + default_timeout=60.0, + client_info=_client_info, + ), + self.preview_update_game_server_cluster: gapic_v1.method.wrap_method( + self.preview_update_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" 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 7c230e10..b3130ac2 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 @@ -57,7 +57,8 @@ def __init__( scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None ) -> None: """Instantiate the transport. @@ -84,6 +85,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -106,7 +109,9 @@ def __init__( ) if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) # Create SSL credentials with client_cert_source or application # default SSL credentials. @@ -125,18 +130,20 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) + self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) - self._stubs = {} # type: Dict[str, Callable] - @classmethod def create_channel( cls, @@ -144,6 +151,7 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs ) -> grpc.Channel: """Create and return a gRPC channel object. @@ -160,6 +168,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -175,6 +185,7 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, + quota_project_id=quota_project_id, **kwargs ) @@ -235,7 +246,7 @@ def list_game_server_clusters( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/ListGameServerClusters", request_serializer=game_server_clusters.ListGameServerClustersRequest.serialize, response_deserializer=game_server_clusters.ListGameServerClustersResponse.deserialize, ) @@ -264,7 +275,7 @@ def get_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/GetGameServerCluster", request_serializer=game_server_clusters.GetGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.GameServerCluster.deserialize, ) @@ -293,7 +304,7 @@ def create_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/CreateGameServerCluster", request_serializer=game_server_clusters.CreateGameServerClusterRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -326,7 +337,7 @@ def preview_create_game_server_cluster( self._stubs[ "preview_create_game_server_cluster" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewCreateGameServerCluster", + "/google.cloud.gaming.v1.GameServerClustersService/PreviewCreateGameServerCluster", request_serializer=game_server_clusters.PreviewCreateGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.PreviewCreateGameServerClusterResponse.deserialize, ) @@ -354,7 +365,7 @@ def delete_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/DeleteGameServerCluster", request_serializer=game_server_clusters.DeleteGameServerClusterRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -386,7 +397,7 @@ def preview_delete_game_server_cluster( self._stubs[ "preview_delete_game_server_cluster" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewDeleteGameServerCluster", + "/google.cloud.gaming.v1.GameServerClustersService/PreviewDeleteGameServerCluster", request_serializer=game_server_clusters.PreviewDeleteGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.PreviewDeleteGameServerClusterResponse.deserialize, ) @@ -414,7 +425,7 @@ def update_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/UpdateGameServerCluster", request_serializer=game_server_clusters.UpdateGameServerClusterRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -446,7 +457,7 @@ def preview_update_game_server_cluster( self._stubs[ "preview_update_game_server_cluster" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewUpdateGameServerCluster", + "/google.cloud.gaming.v1.GameServerClustersService/PreviewUpdateGameServerCluster", request_serializer=game_server_clusters.PreviewUpdateGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.PreviewUpdateGameServerClusterResponse.deserialize, ) 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 index bc9b7a78..4b8e913f 100644 --- 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 @@ -56,7 +56,8 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - **kwargs + quota_project_id: Optional[str] = None, + **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: @@ -72,6 +73,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -83,7 +86,8 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, - **kwargs + quota_project_id=quota_project_id, + **kwargs, ) def __init__( @@ -95,7 +99,8 @@ def __init__( scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, ) -> None: """Instantiate the transport. @@ -123,6 +128,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -161,6 +168,7 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) # Run the base constructor. @@ -169,6 +177,7 @@ def __init__( credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) self._stubs = {} @@ -230,7 +239,7 @@ def list_game_server_clusters( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/ListGameServerClusters", request_serializer=game_server_clusters.ListGameServerClustersRequest.serialize, response_deserializer=game_server_clusters.ListGameServerClustersResponse.deserialize, ) @@ -259,7 +268,7 @@ def get_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/GetGameServerCluster", request_serializer=game_server_clusters.GetGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.GameServerCluster.deserialize, ) @@ -289,7 +298,7 @@ def create_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/CreateGameServerCluster", request_serializer=game_server_clusters.CreateGameServerClusterRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -322,7 +331,7 @@ def preview_create_game_server_cluster( self._stubs[ "preview_create_game_server_cluster" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewCreateGameServerCluster", + "/google.cloud.gaming.v1.GameServerClustersService/PreviewCreateGameServerCluster", request_serializer=game_server_clusters.PreviewCreateGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.PreviewCreateGameServerClusterResponse.deserialize, ) @@ -351,7 +360,7 @@ def delete_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/DeleteGameServerCluster", request_serializer=game_server_clusters.DeleteGameServerClusterRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -383,7 +392,7 @@ def preview_delete_game_server_cluster( self._stubs[ "preview_delete_game_server_cluster" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewDeleteGameServerCluster", + "/google.cloud.gaming.v1.GameServerClustersService/PreviewDeleteGameServerCluster", request_serializer=game_server_clusters.PreviewDeleteGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.PreviewDeleteGameServerClusterResponse.deserialize, ) @@ -412,7 +421,7 @@ def update_game_server_cluster( # 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", + "/google.cloud.gaming.v1.GameServerClustersService/UpdateGameServerCluster", request_serializer=game_server_clusters.UpdateGameServerClusterRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -444,7 +453,7 @@ def preview_update_game_server_cluster( self._stubs[ "preview_update_game_server_cluster" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerClustersService/PreviewUpdateGameServerCluster", + "/google.cloud.gaming.v1.GameServerClustersService/PreviewUpdateGameServerCluster", request_serializer=game_server_clusters.PreviewUpdateGameServerClusterRequest.serialize, response_deserializer=game_server_clusters.PreviewUpdateGameServerClusterResponse.deserialize, ) 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 index f36e03da..888999da 100644 --- 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 @@ -164,7 +164,13 @@ async def list_game_server_configs( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_game_server_configs, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -241,7 +247,13 @@ async def get_game_server_config( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_game_server_config, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -329,7 +341,7 @@ async def create_game_server_config( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.create_game_server_config, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -427,7 +439,7 @@ async def delete_game_server_config( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_game_server_config, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) 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 7228a69b..acef129e 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 @@ -242,6 +242,7 @@ def __init__( scopes=client_options.scopes, api_mtls_endpoint=client_options.api_endpoint, client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, ) def list_game_server_configs( @@ -286,27 +287,29 @@ def list_game_server_configs( # 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]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_configs.ListGameServerConfigsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.ListGameServerConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.ListGameServerConfigsRequest): + request = game_server_configs.ListGameServerConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + 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.wrap_method( - self._transport.list_game_server_configs, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_game_server_configs] # Certain fields should be provided within the metadata header; # add these here. @@ -363,27 +366,29 @@ def get_game_server_config( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_configs.GetGameServerConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.GetGameServerConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.GetGameServerConfigRequest): + request = game_server_configs.GetGameServerConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.get_game_server_config, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_game_server_config] # Certain fields should be provided within the metadata header; # add these here. @@ -449,29 +454,33 @@ def create_game_server_config( # 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]): + has_flattened_params = any([parent, game_server_config]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_configs.CreateGameServerConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.CreateGameServerConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.CreateGameServerConfigRequest): + request = game_server_configs.CreateGameServerConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.create_game_server_config, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.create_game_server_config + ] # Certain fields should be provided within the metadata header; # add these here. @@ -549,27 +558,31 @@ def delete_game_server_config( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_configs.DeleteGameServerConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.DeleteGameServerConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.DeleteGameServerConfigRequest): + request = game_server_configs.DeleteGameServerConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.delete_game_server_config, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.delete_game_server_config + ] # Certain fields should be provided within the metadata header; # add these here. 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 158f8d60..dcf1277a 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 @@ -17,9 +17,12 @@ import abc import typing +import pkg_resources from google import auth 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.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -27,6 +30,16 @@ from google.longrunning import operations_pb2 as operations # type: ignore +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() + + class GameServerConfigsServiceTransport(abc.ABC): """Abstract transport class for GameServerConfigsService.""" @@ -39,6 +52,7 @@ def __init__( credentials: credentials.Credentials = None, credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -54,6 +68,8 @@ def __init__( 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -69,14 +85,57 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes + credentials_file, scopes=scopes, quota_project_id=quota_project_id ) + elif credentials is None: - credentials, _ = auth.default(scopes=scopes) + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_game_server_configs: gapic_v1.method.wrap_method( + self.list_game_server_configs, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_config: gapic_v1.method.wrap_method( + self.get_game_server_config, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_game_server_config: gapic_v1.method.wrap_method( + self.create_game_server_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_game_server_config: gapic_v1.method.wrap_method( + self.delete_game_server_config, + default_timeout=60.0, + client_info=_client_info, + ), + } + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" 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 473cce24..9f93e147 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 @@ -57,7 +57,8 @@ def __init__( scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None ) -> None: """Instantiate the transport. @@ -84,6 +85,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -106,7 +109,9 @@ def __init__( ) if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) # Create SSL credentials with client_cert_source or application # default SSL credentials. @@ -125,18 +130,20 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) + self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) - self._stubs = {} # type: Dict[str, Callable] - @classmethod def create_channel( cls, @@ -144,6 +151,7 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs ) -> grpc.Channel: """Create and return a gRPC channel object. @@ -160,6 +168,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -175,6 +185,7 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, + quota_project_id=quota_project_id, **kwargs ) @@ -235,7 +246,7 @@ def list_game_server_configs( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/ListGameServerConfigs", request_serializer=game_server_configs.ListGameServerConfigsRequest.serialize, response_deserializer=game_server_configs.ListGameServerConfigsResponse.deserialize, ) @@ -264,7 +275,7 @@ def get_game_server_config( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/GetGameServerConfig", request_serializer=game_server_configs.GetGameServerConfigRequest.serialize, response_deserializer=game_server_configs.GameServerConfig.deserialize, ) @@ -296,7 +307,7 @@ def create_game_server_config( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/CreateGameServerConfig", request_serializer=game_server_configs.CreateGameServerConfigRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -326,7 +337,7 @@ def delete_game_server_config( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/DeleteGameServerConfig", request_serializer=game_server_configs.DeleteGameServerConfigRequest.serialize, response_deserializer=operations.Operation.FromString, ) 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 index c97ac06e..b0043929 100644 --- 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 @@ -56,7 +56,8 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - **kwargs + quota_project_id: Optional[str] = None, + **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: @@ -72,6 +73,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -83,7 +86,8 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, - **kwargs + quota_project_id=quota_project_id, + **kwargs, ) def __init__( @@ -95,7 +99,8 @@ def __init__( scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, ) -> None: """Instantiate the transport. @@ -123,6 +128,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -161,6 +168,7 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) # Run the base constructor. @@ -169,6 +177,7 @@ def __init__( credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) self._stubs = {} @@ -230,7 +239,7 @@ def list_game_server_configs( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/ListGameServerConfigs", request_serializer=game_server_configs.ListGameServerConfigsRequest.serialize, response_deserializer=game_server_configs.ListGameServerConfigsResponse.deserialize, ) @@ -259,7 +268,7 @@ def get_game_server_config( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/GetGameServerConfig", request_serializer=game_server_configs.GetGameServerConfigRequest.serialize, response_deserializer=game_server_configs.GameServerConfig.deserialize, ) @@ -292,7 +301,7 @@ def create_game_server_config( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/CreateGameServerConfig", request_serializer=game_server_configs.CreateGameServerConfigRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -323,7 +332,7 @@ def delete_game_server_config( # 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", + "/google.cloud.gaming.v1.GameServerConfigsService/DeleteGameServerConfig", request_serializer=game_server_configs.DeleteGameServerConfigRequest.serialize, response_deserializer=operations.Operation.FromString, ) 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 index d4c90638..13a2470d 100644 --- 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 @@ -170,7 +170,13 @@ async def list_game_server_deployments( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_game_server_deployments, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -247,7 +253,13 @@ async def get_game_server_deployment( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_game_server_deployment, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -331,7 +343,7 @@ async def create_game_server_deployment( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.create_game_server_deployment, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -427,7 +439,7 @@ async def delete_game_server_deployment( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_game_server_deployment, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -523,7 +535,7 @@ async def update_game_server_deployment( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_game_server_deployment, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -607,7 +619,13 @@ async def get_game_server_deployment_rollout( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_game_server_deployment_rollout, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -703,7 +721,7 @@ async def update_game_server_deployment_rollout( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_game_server_deployment_rollout, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -769,7 +787,13 @@ async def preview_game_server_deployment_rollout( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.preview_game_server_deployment_rollout, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -825,7 +849,13 @@ async def fetch_deployment_state( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.fetch_deployment_state, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=120.0, client_info=_client_info, ) 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 b4eae774..20221142 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 @@ -265,6 +265,7 @@ def __init__( scopes=client_options.scopes, api_mtls_endpoint=client_options.api_endpoint, client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, ) def list_game_server_deployments( @@ -308,27 +309,33 @@ def list_game_server_deployments( # 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]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_deployments.ListGameServerDeploymentsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.ListGameServerDeploymentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.ListGameServerDeploymentsRequest + ): + request = game_server_deployments.ListGameServerDeploymentsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + 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.wrap_method( - self._transport.list_game_server_deployments, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.list_game_server_deployments + ] # Certain fields should be provided within the metadata header; # add these here. @@ -385,27 +392,33 @@ def get_game_server_deployment( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_deployments.GetGameServerDeploymentRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.GetGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.GetGameServerDeploymentRequest + ): + request = game_server_deployments.GetGameServerDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.get_game_server_deployment, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.get_game_server_deployment + ] # Certain fields should be provided within the metadata header; # add these here. @@ -467,29 +480,35 @@ def create_game_server_deployment( # 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]): + has_flattened_params = any([parent, game_server_deployment]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_deployments.CreateGameServerDeploymentRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.CreateGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.CreateGameServerDeploymentRequest + ): + request = game_server_deployments.CreateGameServerDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.create_game_server_deployment, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.create_game_server_deployment + ] # Certain fields should be provided within the metadata header; # add these here. @@ -565,27 +584,33 @@ def delete_game_server_deployment( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_deployments.DeleteGameServerDeploymentRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.DeleteGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.DeleteGameServerDeploymentRequest + ): + request = game_server_deployments.DeleteGameServerDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.delete_game_server_deployment, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.delete_game_server_deployment + ] # Certain fields should be provided within the metadata header; # add these here. @@ -659,29 +684,35 @@ def update_game_server_deployment( # 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]): + has_flattened_params = any([game_server_deployment, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_deployments.UpdateGameServerDeploymentRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.UpdateGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.UpdateGameServerDeploymentRequest + ): + request = game_server_deployments.UpdateGameServerDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.update_game_server_deployment, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_game_server_deployment + ] # Certain fields should be provided within the metadata header; # add these here. @@ -745,27 +776,35 @@ def get_game_server_deployment_rollout( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_deployments.GetGameServerDeploymentRolloutRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.GetGameServerDeploymentRolloutRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.GetGameServerDeploymentRolloutRequest + ): + request = game_server_deployments.GetGameServerDeploymentRolloutRequest( + request + ) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.get_game_server_deployment_rollout, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.get_game_server_deployment_rollout + ] # Certain fields should be provided within the metadata header; # add these here. @@ -837,31 +876,37 @@ def update_game_server_deployment_rollout( # 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]): + has_flattened_params = any([rollout, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = game_server_deployments.UpdateGameServerDeploymentRolloutRequest( - request - ) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.UpdateGameServerDeploymentRolloutRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.UpdateGameServerDeploymentRolloutRequest + ): + request = game_server_deployments.UpdateGameServerDeploymentRolloutRequest( + request + ) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.update_game_server_deployment_rollout, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_game_server_deployment_rollout + ] # Certain fields should be provided within the metadata header; # add these here. @@ -917,17 +962,22 @@ def preview_game_server_deployment_rollout( """ # Create or coerce a protobuf request object. - request = game_server_deployments.PreviewGameServerDeploymentRolloutRequest( - request - ) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.PreviewGameServerDeploymentRolloutRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.PreviewGameServerDeploymentRolloutRequest + ): + request = game_server_deployments.PreviewGameServerDeploymentRolloutRequest( + request + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.preview_game_server_deployment_rollout, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.preview_game_server_deployment_rollout + ] # Certain fields should be provided within the metadata header; # add these here. @@ -975,15 +1025,16 @@ def fetch_deployment_state( """ # Create or coerce a protobuf request object. - request = game_server_deployments.FetchDeploymentStateRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.FetchDeploymentStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_deployments.FetchDeploymentStateRequest): + request = game_server_deployments.FetchDeploymentStateRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.fetch_deployment_state, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.fetch_deployment_state] # Certain fields should be provided within the metadata header; # add these here. 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 6004e163..adfdac58 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 @@ -17,9 +17,12 @@ import abc import typing +import pkg_resources from google import auth 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.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -27,6 +30,16 @@ from google.longrunning import operations_pb2 as operations # type: ignore +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() + + class GameServerDeploymentsServiceTransport(abc.ABC): """Abstract transport class for GameServerDeploymentsService.""" @@ -39,6 +52,7 @@ def __init__( credentials: credentials.Credentials = None, credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -54,6 +68,8 @@ def __init__( 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -69,14 +85,100 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes + credentials_file, scopes=scopes, quota_project_id=quota_project_id ) + elif credentials is None: - credentials, _ = auth.default(scopes=scopes) + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_game_server_deployments: gapic_v1.method.wrap_method( + self.list_game_server_deployments, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_deployment: gapic_v1.method.wrap_method( + self.get_game_server_deployment, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_game_server_deployment: gapic_v1.method.wrap_method( + self.create_game_server_deployment, + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_game_server_deployment: gapic_v1.method.wrap_method( + self.delete_game_server_deployment, + default_timeout=60.0, + client_info=_client_info, + ), + self.update_game_server_deployment: gapic_v1.method.wrap_method( + self.update_game_server_deployment, + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_deployment_rollout: gapic_v1.method.wrap_method( + self.get_game_server_deployment_rollout, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_game_server_deployment_rollout: gapic_v1.method.wrap_method( + self.update_game_server_deployment_rollout, + default_timeout=60.0, + client_info=_client_info, + ), + self.preview_game_server_deployment_rollout: gapic_v1.method.wrap_method( + self.preview_game_server_deployment_rollout, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.fetch_deployment_state: gapic_v1.method.wrap_method( + self.fetch_deployment_state, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=120.0, + client_info=_client_info, + ), + } + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" 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 ce9f53f6..80f479de 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 @@ -57,7 +57,8 @@ def __init__( scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None ) -> None: """Instantiate the transport. @@ -84,6 +85,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -106,7 +109,9 @@ def __init__( ) if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) # Create SSL credentials with client_cert_source or application # default SSL credentials. @@ -125,18 +130,20 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) + self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) - self._stubs = {} # type: Dict[str, Callable] - @classmethod def create_channel( cls, @@ -144,6 +151,7 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs ) -> grpc.Channel: """Create and return a gRPC channel object. @@ -160,6 +168,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -175,6 +185,7 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, + quota_project_id=quota_project_id, **kwargs ) @@ -235,7 +246,7 @@ def list_game_server_deployments( # 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", + "/google.cloud.gaming.v1.GameServerDeploymentsService/ListGameServerDeployments", request_serializer=game_server_deployments.ListGameServerDeploymentsRequest.serialize, response_deserializer=game_server_deployments.ListGameServerDeploymentsResponse.deserialize, ) @@ -264,7 +275,7 @@ def get_game_server_deployment( # 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", + "/google.cloud.gaming.v1.GameServerDeploymentsService/GetGameServerDeployment", request_serializer=game_server_deployments.GetGameServerDeploymentRequest.serialize, response_deserializer=game_server_deployments.GameServerDeployment.deserialize, ) @@ -296,7 +307,7 @@ def create_game_server_deployment( self._stubs[ "create_game_server_deployment" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/CreateGameServerDeployment", + "/google.cloud.gaming.v1.GameServerDeploymentsService/CreateGameServerDeployment", request_serializer=game_server_deployments.CreateGameServerDeploymentRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -327,7 +338,7 @@ def delete_game_server_deployment( self._stubs[ "delete_game_server_deployment" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/DeleteGameServerDeployment", + "/google.cloud.gaming.v1.GameServerDeploymentsService/DeleteGameServerDeployment", request_serializer=game_server_deployments.DeleteGameServerDeploymentRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -358,7 +369,7 @@ def update_game_server_deployment( self._stubs[ "update_game_server_deployment" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/UpdateGameServerDeployment", + "/google.cloud.gaming.v1.GameServerDeploymentsService/UpdateGameServerDeployment", request_serializer=game_server_deployments.UpdateGameServerDeploymentRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -390,7 +401,7 @@ def get_game_server_deployment_rollout( self._stubs[ "get_game_server_deployment_rollout" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/GetGameServerDeploymentRollout", + "/google.cloud.gaming.v1.GameServerDeploymentsService/GetGameServerDeploymentRollout", request_serializer=game_server_deployments.GetGameServerDeploymentRolloutRequest.serialize, response_deserializer=game_server_deployments.GameServerDeploymentRollout.deserialize, ) @@ -428,7 +439,7 @@ def update_game_server_deployment_rollout( self._stubs[ "update_game_server_deployment_rollout" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/UpdateGameServerDeploymentRollout", + "/google.cloud.gaming.v1.GameServerDeploymentsService/UpdateGameServerDeploymentRollout", request_serializer=game_server_deployments.UpdateGameServerDeploymentRolloutRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -461,7 +472,7 @@ def preview_game_server_deployment_rollout( self._stubs[ "preview_game_server_deployment_rollout" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/PreviewGameServerDeploymentRollout", + "/google.cloud.gaming.v1.GameServerDeploymentsService/PreviewGameServerDeploymentRollout", request_serializer=game_server_deployments.PreviewGameServerDeploymentRolloutRequest.serialize, response_deserializer=game_server_deployments.PreviewGameServerDeploymentRolloutResponse.deserialize, ) @@ -493,7 +504,7 @@ def fetch_deployment_state( # 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", + "/google.cloud.gaming.v1.GameServerDeploymentsService/FetchDeploymentState", request_serializer=game_server_deployments.FetchDeploymentStateRequest.serialize, response_deserializer=game_server_deployments.FetchDeploymentStateResponse.deserialize, ) 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 index 5623d47f..108e6391 100644 --- 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 @@ -58,7 +58,8 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - **kwargs + quota_project_id: Optional[str] = None, + **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: @@ -74,6 +75,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -85,7 +88,8 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, - **kwargs + quota_project_id=quota_project_id, + **kwargs, ) def __init__( @@ -97,7 +101,8 @@ def __init__( scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, ) -> None: """Instantiate the transport. @@ -125,6 +130,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -163,6 +170,7 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) # Run the base constructor. @@ -171,6 +179,7 @@ def __init__( credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) self._stubs = {} @@ -232,7 +241,7 @@ def list_game_server_deployments( # 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", + "/google.cloud.gaming.v1.GameServerDeploymentsService/ListGameServerDeployments", request_serializer=game_server_deployments.ListGameServerDeploymentsRequest.serialize, response_deserializer=game_server_deployments.ListGameServerDeploymentsResponse.deserialize, ) @@ -261,7 +270,7 @@ def get_game_server_deployment( # 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", + "/google.cloud.gaming.v1.GameServerDeploymentsService/GetGameServerDeployment", request_serializer=game_server_deployments.GetGameServerDeploymentRequest.serialize, response_deserializer=game_server_deployments.GameServerDeployment.deserialize, ) @@ -293,7 +302,7 @@ def create_game_server_deployment( self._stubs[ "create_game_server_deployment" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/CreateGameServerDeployment", + "/google.cloud.gaming.v1.GameServerDeploymentsService/CreateGameServerDeployment", request_serializer=game_server_deployments.CreateGameServerDeploymentRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -324,7 +333,7 @@ def delete_game_server_deployment( self._stubs[ "delete_game_server_deployment" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/DeleteGameServerDeployment", + "/google.cloud.gaming.v1.GameServerDeploymentsService/DeleteGameServerDeployment", request_serializer=game_server_deployments.DeleteGameServerDeploymentRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -355,7 +364,7 @@ def update_game_server_deployment( self._stubs[ "update_game_server_deployment" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/UpdateGameServerDeployment", + "/google.cloud.gaming.v1.GameServerDeploymentsService/UpdateGameServerDeployment", request_serializer=game_server_deployments.UpdateGameServerDeploymentRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -387,7 +396,7 @@ def get_game_server_deployment_rollout( self._stubs[ "get_game_server_deployment_rollout" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/GetGameServerDeploymentRollout", + "/google.cloud.gaming.v1.GameServerDeploymentsService/GetGameServerDeploymentRollout", request_serializer=game_server_deployments.GetGameServerDeploymentRolloutRequest.serialize, response_deserializer=game_server_deployments.GameServerDeploymentRollout.deserialize, ) @@ -425,7 +434,7 @@ def update_game_server_deployment_rollout( self._stubs[ "update_game_server_deployment_rollout" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/UpdateGameServerDeploymentRollout", + "/google.cloud.gaming.v1.GameServerDeploymentsService/UpdateGameServerDeploymentRollout", request_serializer=game_server_deployments.UpdateGameServerDeploymentRolloutRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -458,7 +467,7 @@ def preview_game_server_deployment_rollout( self._stubs[ "preview_game_server_deployment_rollout" ] = self.grpc_channel.unary_unary( - "/google.cloud.gaming.v1beta.GameServerDeploymentsService/PreviewGameServerDeploymentRollout", + "/google.cloud.gaming.v1.GameServerDeploymentsService/PreviewGameServerDeploymentRollout", request_serializer=game_server_deployments.PreviewGameServerDeploymentRolloutRequest.serialize, response_deserializer=game_server_deployments.PreviewGameServerDeploymentRolloutResponse.deserialize, ) @@ -490,7 +499,7 @@ def fetch_deployment_state( # 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", + "/google.cloud.gaming.v1.GameServerDeploymentsService/FetchDeploymentState", request_serializer=game_server_deployments.FetchDeploymentStateRequest.serialize, response_deserializer=game_server_deployments.FetchDeploymentStateResponse.deserialize, ) diff --git a/google/cloud/gaming_v1/services/realms_service/async_client.py b/google/cloud/gaming_v1/services/realms_service/async_client.py index 07eb9dfd..84a8ebdf 100644 --- a/google/cloud/gaming_v1/services/realms_service/async_client.py +++ b/google/cloud/gaming_v1/services/realms_service/async_client.py @@ -160,7 +160,13 @@ async def list_realms( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_realms, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -236,7 +242,13 @@ async def get_realm( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_realm, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) @@ -327,7 +339,7 @@ async def create_realm( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.create_realm, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -422,7 +434,7 @@ async def delete_realm( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_realm, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -515,7 +527,7 @@ async def update_realm( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_realm, - default_timeout=None, + default_timeout=60.0, client_info=_client_info, ) @@ -576,7 +588,13 @@ async def preview_realm_update( # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.preview_realm_update, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, client_info=_client_info, ) diff --git a/google/cloud/gaming_v1/services/realms_service/client.py b/google/cloud/gaming_v1/services/realms_service/client.py index 38f71642..c83108ca 100644 --- a/google/cloud/gaming_v1/services/realms_service/client.py +++ b/google/cloud/gaming_v1/services/realms_service/client.py @@ -237,6 +237,7 @@ def __init__( scopes=client_options.scopes, api_mtls_endpoint=client_options.api_endpoint, client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, ) def list_realms( @@ -279,25 +280,29 @@ def list_realms( # 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]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = realms.ListRealmsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a realms.ListRealmsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.ListRealmsRequest): + request = realms.ListRealmsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + 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.wrap_method( - self._transport.list_realms, default_timeout=None, client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_realms] # Certain fields should be provided within the metadata header; # add these here. @@ -353,25 +358,29 @@ def get_realm( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = realms.GetRealmRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a realms.GetRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.GetRealmRequest): + request = realms.GetRealmRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.get_realm, default_timeout=None, client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_realm] # Certain fields should be provided within the metadata header; # add these here. @@ -438,31 +447,33 @@ def create_realm( # 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]): + has_flattened_params = any([parent, realm, realm_id]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = realms.CreateRealmRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a realms.CreateRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.CreateRealmRequest): + request = realms.CreateRealmRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.create_realm, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_realm] # Certain fields should be provided within the metadata header; # add these here. @@ -537,27 +548,29 @@ def delete_realm( # 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]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = realms.DeleteRealmRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a realms.DeleteRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.DeleteRealmRequest): + request = realms.DeleteRealmRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + 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.wrap_method( - self._transport.delete_realm, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_realm] # Certain fields should be provided within the metadata header; # add these here. @@ -628,29 +641,31 @@ def update_realm( # 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]): + has_flattened_params = any([realm, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = realms.UpdateRealmRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a realms.UpdateRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.UpdateRealmRequest): + request = realms.UpdateRealmRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # 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 + 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.wrap_method( - self._transport.update_realm, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_realm] # Certain fields should be provided within the metadata header; # add these here. @@ -703,15 +718,16 @@ def preview_realm_update( """ # Create or coerce a protobuf request object. - request = realms.PreviewRealmUpdateRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a realms.PreviewRealmUpdateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.PreviewRealmUpdateRequest): + request = realms.PreviewRealmUpdateRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.preview_realm_update, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.preview_realm_update] # Certain fields should be provided within the metadata header; # add these here. 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 33b97793..22f3a166 100644 --- a/google/cloud/gaming_v1/services/realms_service/transports/base.py +++ b/google/cloud/gaming_v1/services/realms_service/transports/base.py @@ -17,9 +17,12 @@ import abc import typing +import pkg_resources from google import auth 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.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -27,6 +30,16 @@ from google.longrunning import operations_pb2 as operations # type: ignore +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() + + class RealmsServiceTransport(abc.ABC): """Abstract transport class for RealmsService.""" @@ -39,6 +52,7 @@ def __init__( credentials: credentials.Credentials = None, credentials_file: typing.Optional[str] = None, scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, **kwargs, ) -> None: """Instantiate the transport. @@ -54,6 +68,8 @@ def __init__( 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -69,14 +85,67 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes + credentials_file, scopes=scopes, quota_project_id=quota_project_id ) + elif credentials is None: - credentials, _ = auth.default(scopes=scopes) + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_realms: gapic_v1.method.wrap_method( + self.list_realms, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_realm: gapic_v1.method.wrap_method( + self.get_realm, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_realm: gapic_v1.method.wrap_method( + self.create_realm, default_timeout=60.0, client_info=_client_info, + ), + self.delete_realm: gapic_v1.method.wrap_method( + self.delete_realm, default_timeout=60.0, client_info=_client_info, + ), + self.update_realm: gapic_v1.method.wrap_method( + self.update_realm, default_timeout=60.0, client_info=_client_info, + ), + self.preview_realm_update: gapic_v1.method.wrap_method( + self.preview_realm_update, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" 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 d4095864..7f6bfee0 100644 --- a/google/cloud/gaming_v1/services/realms_service/transports/grpc.py +++ b/google/cloud/gaming_v1/services/realms_service/transports/grpc.py @@ -57,7 +57,8 @@ def __init__( scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None ) -> None: """Instantiate the transport. @@ -84,6 +85,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport @@ -106,7 +109,9 @@ def __init__( ) if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) # Create SSL credentials with client_cert_source or application # default SSL credentials. @@ -125,18 +130,20 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) + self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) - self._stubs = {} # type: Dict[str, Callable] - @classmethod def create_channel( cls, @@ -144,6 +151,7 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, **kwargs ) -> grpc.Channel: """Create and return a gRPC channel object. @@ -160,6 +168,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -175,6 +185,7 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, + quota_project_id=quota_project_id, **kwargs ) @@ -231,7 +242,7 @@ def list_realms( # 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", + "/google.cloud.gaming.v1.RealmsService/ListRealms", request_serializer=realms.ListRealmsRequest.serialize, response_deserializer=realms.ListRealmsResponse.deserialize, ) @@ -255,7 +266,7 @@ def get_realm(self) -> Callable[[realms.GetRealmRequest], realms.Realm]: # 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", + "/google.cloud.gaming.v1.RealmsService/GetRealm", request_serializer=realms.GetRealmRequest.serialize, response_deserializer=realms.Realm.deserialize, ) @@ -281,7 +292,7 @@ def create_realm( # 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", + "/google.cloud.gaming.v1.RealmsService/CreateRealm", request_serializer=realms.CreateRealmRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -307,7 +318,7 @@ def delete_realm( # 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", + "/google.cloud.gaming.v1.RealmsService/DeleteRealm", request_serializer=realms.DeleteRealmRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -333,7 +344,7 @@ def update_realm( # 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", + "/google.cloud.gaming.v1.RealmsService/UpdateRealm", request_serializer=realms.UpdateRealmRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -361,7 +372,7 @@ def preview_realm_update( # 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", + "/google.cloud.gaming.v1.RealmsService/PreviewRealmUpdate", request_serializer=realms.PreviewRealmUpdateRequest.serialize, response_deserializer=realms.PreviewRealmUpdateResponse.deserialize, ) 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 index d0f618c3..6ab59c59 100644 --- a/google/cloud/gaming_v1/services/realms_service/transports/grpc_asyncio.py +++ b/google/cloud/gaming_v1/services/realms_service/transports/grpc_asyncio.py @@ -56,7 +56,8 @@ def create_channel( credentials: credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - **kwargs + quota_project_id: Optional[str] = None, + **kwargs, ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: @@ -72,6 +73,8 @@ def create_channel( scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: @@ -83,7 +86,8 @@ def create_channel( credentials=credentials, credentials_file=credentials_file, scopes=scopes, - **kwargs + quota_project_id=quota_project_id, + **kwargs, ) def __init__( @@ -95,7 +99,8 @@ def __init__( scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, ) -> None: """Instantiate the transport. @@ -123,6 +128,8 @@ def __init__( callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport @@ -161,6 +168,7 @@ def __init__( credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) # Run the base constructor. @@ -169,6 +177,7 @@ def __init__( credentials=credentials, credentials_file=credentials_file, scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) self._stubs = {} @@ -226,7 +235,7 @@ def list_realms( # 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", + "/google.cloud.gaming.v1.RealmsService/ListRealms", request_serializer=realms.ListRealmsRequest.serialize, response_deserializer=realms.ListRealmsResponse.deserialize, ) @@ -250,7 +259,7 @@ def get_realm(self) -> Callable[[realms.GetRealmRequest], Awaitable[realms.Realm # 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", + "/google.cloud.gaming.v1.RealmsService/GetRealm", request_serializer=realms.GetRealmRequest.serialize, response_deserializer=realms.Realm.deserialize, ) @@ -276,7 +285,7 @@ def create_realm( # 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", + "/google.cloud.gaming.v1.RealmsService/CreateRealm", request_serializer=realms.CreateRealmRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -302,7 +311,7 @@ def delete_realm( # 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", + "/google.cloud.gaming.v1.RealmsService/DeleteRealm", request_serializer=realms.DeleteRealmRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -328,7 +337,7 @@ def update_realm( # 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", + "/google.cloud.gaming.v1.RealmsService/UpdateRealm", request_serializer=realms.UpdateRealmRequest.serialize, response_deserializer=operations.Operation.FromString, ) @@ -356,7 +365,7 @@ def preview_realm_update( # 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", + "/google.cloud.gaming.v1.RealmsService/PreviewRealmUpdate", request_serializer=realms.PreviewRealmUpdateRequest.serialize, response_deserializer=realms.PreviewRealmUpdateResponse.deserialize, ) diff --git a/google/cloud/gaming_v1/types/__init__.py b/google/cloud/gaming_v1/types/__init__.py index 28428851..fea9d663 100644 --- a/google/cloud/gaming_v1/types/__init__.py +++ b/google/cloud/gaming_v1/types/__init__.py @@ -26,27 +26,6 @@ TargetState, DeployedFleetDetails, ) -from .game_server_configs import ( - ListGameServerConfigsRequest, - ListGameServerConfigsResponse, - GetGameServerConfigRequest, - CreateGameServerConfigRequest, - DeleteGameServerConfigRequest, - ScalingConfig, - FleetConfig, - GameServerConfig, -) -from .realms import ( - ListRealmsRequest, - ListRealmsResponse, - GetRealmRequest, - CreateRealmRequest, - DeleteRealmRequest, - UpdateRealmRequest, - PreviewRealmUpdateRequest, - PreviewRealmUpdateResponse, - Realm, -) from .game_server_clusters import ( ListGameServerClustersRequest, ListGameServerClustersResponse, @@ -64,6 +43,16 @@ GkeClusterReference, GameServerCluster, ) +from .game_server_configs import ( + ListGameServerConfigsRequest, + ListGameServerConfigsResponse, + GetGameServerConfigRequest, + CreateGameServerConfigRequest, + DeleteGameServerConfigRequest, + ScalingConfig, + FleetConfig, + GameServerConfig, +) from .game_server_deployments import ( ListGameServerDeploymentsRequest, ListGameServerDeploymentsResponse, @@ -81,6 +70,17 @@ PreviewGameServerDeploymentRolloutRequest, PreviewGameServerDeploymentRolloutResponse, ) +from .realms import ( + ListRealmsRequest, + ListRealmsResponse, + GetRealmRequest, + CreateRealmRequest, + DeleteRealmRequest, + UpdateRealmRequest, + PreviewRealmUpdateRequest, + PreviewRealmUpdateResponse, + Realm, +) __all__ = ( @@ -93,23 +93,6 @@ "TargetDetails", "TargetState", "DeployedFleetDetails", - "ListGameServerConfigsRequest", - "ListGameServerConfigsResponse", - "GetGameServerConfigRequest", - "CreateGameServerConfigRequest", - "DeleteGameServerConfigRequest", - "ScalingConfig", - "FleetConfig", - "GameServerConfig", - "ListRealmsRequest", - "ListRealmsResponse", - "GetRealmRequest", - "CreateRealmRequest", - "DeleteRealmRequest", - "UpdateRealmRequest", - "PreviewRealmUpdateRequest", - "PreviewRealmUpdateResponse", - "Realm", "ListGameServerClustersRequest", "ListGameServerClustersResponse", "GetGameServerClusterRequest", @@ -125,6 +108,14 @@ "GameServerClusterConnectionInfo", "GkeClusterReference", "GameServerCluster", + "ListGameServerConfigsRequest", + "ListGameServerConfigsResponse", + "GetGameServerConfigRequest", + "CreateGameServerConfigRequest", + "DeleteGameServerConfigRequest", + "ScalingConfig", + "FleetConfig", + "GameServerConfig", "ListGameServerDeploymentsRequest", "ListGameServerDeploymentsResponse", "GetGameServerDeploymentRequest", @@ -140,4 +131,13 @@ "GameServerDeploymentRollout", "PreviewGameServerDeploymentRolloutRequest", "PreviewGameServerDeploymentRolloutResponse", + "ListRealmsRequest", + "ListRealmsResponse", + "GetRealmRequest", + "CreateRealmRequest", + "DeleteRealmRequest", + "UpdateRealmRequest", + "PreviewRealmUpdateRequest", + "PreviewRealmUpdateResponse", + "Realm", ) diff --git a/google/cloud/gaming_v1/types/common.py b/google/cloud/gaming_v1/types/common.py index 839ca1d7..29634e71 100644 --- a/google/cloud/gaming_v1/types/common.py +++ b/google/cloud/gaming_v1/types/common.py @@ -23,7 +23,7 @@ __protobuf__ = proto.module( - package="google.cloud.gaming.v1beta", + package="google.cloud.gaming.v1", manifest={ "OperationMetadata", "OperationStatus", diff --git a/google/cloud/gaming_v1/types/game_server_clusters.py b/google/cloud/gaming_v1/types/game_server_clusters.py index 05f88b09..e4413e14 100644 --- a/google/cloud/gaming_v1/types/game_server_clusters.py +++ b/google/cloud/gaming_v1/types/game_server_clusters.py @@ -24,7 +24,7 @@ __protobuf__ = proto.module( - package="google.cloud.gaming.v1beta", + package="google.cloud.gaming.v1", manifest={ "ListGameServerClustersRequest", "ListGameServerClustersResponse", @@ -59,7 +59,7 @@ class ListGameServerClustersRequest(proto.Message): 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] + [next_page_token][google.cloud.gaming.v1.ListGameServerClustersResponse.next_page_token] to determine if there are more GameServerClusters left to be queried. page_token (str): @@ -90,7 +90,7 @@ class ListGameServerClustersResponse(proto.Message): GameServerClustersService.ListGameServerClusters. Attributes: - game_server_clusters (Sequence[~.gcgv_game_server_clusters.GameServerCluster]): + game_server_clusters (Sequence[~.gcg_game_server_clusters.GameServerCluster]): The list of game server clusters. next_page_token (str): Token to retrieve the next page of results, @@ -139,7 +139,7 @@ class CreateGameServerClusterRequest(proto.Message): game_server_cluster_id (str): Required. The ID of the game server cluster resource to be created. - game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster): + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): Required. The game server cluster resource to be created. """ @@ -164,7 +164,7 @@ class PreviewCreateGameServerClusterRequest(proto.Message): game_server_cluster_id (str): Required. The ID of the game server cluster resource to be created. - game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster): + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): Required. The game server cluster resource to be created. preview_time (~.timestamp.Timestamp): @@ -253,7 +253,7 @@ class UpdateGameServerClusterRequest(proto.Message): GameServerClustersService.UpdateGameServerCluster. Attributes: - game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster): + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): Required. The game server cluster to be updated. Only fields specified in update_mask are updated. update_mask (~.field_mask.FieldMask): @@ -277,7 +277,7 @@ class PreviewUpdateGameServerClusterRequest(proto.Message): GameServerClustersService.UpdateGameServerCluster. Attributes: - game_server_cluster (~.gcgv_game_server_clusters.GameServerCluster): + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): Required. The game server cluster to be updated. Only fields specified in update_mask are updated. update_mask (~.field_mask.FieldMask): @@ -321,7 +321,7 @@ class GameServerClusterConnectionInfo(proto.Message): r"""The game server cluster connection information. Attributes: - gke_cluster_reference (~.gcgv_game_server_clusters.GkeClusterReference): + gke_cluster_reference (~.gcg_game_server_clusters.GkeClusterReference): Reference to the GKE cluster where the game servers are installed. namespace (str): @@ -376,10 +376,10 @@ class GameServerCluster(proto.Message): Output only. The creation time. update_time (~.timestamp.Timestamp): Output only. The last-modified time. - labels (Sequence[~.gcgv_game_server_clusters.GameServerCluster.LabelsEntry]): + labels (Sequence[~.gcg_game_server_clusters.GameServerCluster.LabelsEntry]): The labels associated with this game server cluster. Each label is a key-value pair. - connection_info (~.gcgv_game_server_clusters.GameServerClusterConnectionInfo): + connection_info (~.gcg_game_server_clusters.GameServerClusterConnectionInfo): The game server cluster connection information. This information is used to manage game server clusters. 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 87138f5c..5b368610 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.v1", 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 6f0ebc3d..36eb4d4a 100644 --- a/google/cloud/gaming_v1/types/game_server_configs.py +++ b/google/cloud/gaming_v1/types/game_server_configs.py @@ -23,7 +23,7 @@ __protobuf__ = proto.module( - package="google.cloud.gaming.v1beta", + package="google.cloud.gaming.v1", manifest={ "ListGameServerConfigsRequest", "ListGameServerConfigsResponse", @@ -51,7 +51,7 @@ class ListGameServerConfigsRequest(proto.Message): unspecified, server will pick an appropriate default. Server may return fewer items than requested. A caller should only rely on response's - [next_page_token][google.cloud.gaming.v1beta.ListGameServerConfigsResponse.next_page_token] + [next_page_token][google.cloud.gaming.v1.ListGameServerConfigsResponse.next_page_token] to determine if there are more GameServerConfigs left to be queried. page_token (str): @@ -82,7 +82,7 @@ class ListGameServerConfigsResponse(proto.Message): GameServerConfigsService.ListGameServerConfigs. Attributes: - game_server_configs (Sequence[~.gcgv_game_server_configs.GameServerConfig]): + game_server_configs (Sequence[~.gcg_game_server_configs.GameServerConfig]): The list of game server configs. next_page_token (str): Token to retrieve the next page of results, @@ -132,7 +132,7 @@ class CreateGameServerConfigRequest(proto.Message): config_id (str): Required. The ID of the game server config resource to be created. - game_server_config (~.gcgv_game_server_configs.GameServerConfig): + game_server_config (~.gcg_game_server_configs.GameServerConfig): Required. The game server config resource to be created. """ @@ -224,13 +224,13 @@ class GameServerConfig(proto.Message): Output only. The creation time. update_time (~.timestamp.Timestamp): Output only. The last-modified time. - labels (Sequence[~.gcgv_game_server_configs.GameServerConfig.LabelsEntry]): + labels (Sequence[~.gcg_game_server_configs.GameServerConfig.LabelsEntry]): The labels associated with this game server config. Each label is a key-value pair. - fleet_configs (Sequence[~.gcgv_game_server_configs.FleetConfig]): + fleet_configs (Sequence[~.gcg_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]): + scaling_configs (Sequence[~.gcg_game_server_configs.ScalingConfig]): The autoscaling settings. description (str): The description of the game server config. 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 87138f5c..5b368610 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.v1", 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 6e7db91b..ea03de7e 100644 --- a/google/cloud/gaming_v1/types/game_server_deployments.py +++ b/google/cloud/gaming_v1/types/game_server_deployments.py @@ -24,7 +24,7 @@ __protobuf__ = proto.module( - package="google.cloud.gaming.v1beta", + package="google.cloud.gaming.v1", manifest={ "ListGameServerDeploymentsRequest", "ListGameServerDeploymentsResponse", @@ -58,7 +58,7 @@ class ListGameServerDeploymentsRequest(proto.Message): 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] + [next_page_token][google.cloud.gaming.v1.ListGameServerDeploymentsResponse.next_page_token] to determine if there are more GameServerDeployments left to be queried. page_token (str): @@ -89,7 +89,7 @@ class ListGameServerDeploymentsResponse(proto.Message): GameServerDeploymentsService.ListGameServerDeployments. Attributes: - game_server_deployments (Sequence[~.gcgv_game_server_deployments.GameServerDeployment]): + game_server_deployments (Sequence[~.gcg_game_server_deployments.GameServerDeployment]): The list of game server deployments. next_page_token (str): Token to retrieve the next page of results, @@ -153,7 +153,7 @@ class CreateGameServerDeploymentRequest(proto.Message): deployment_id (str): Required. The ID of the game server delpoyment resource to be created. - game_server_deployment (~.gcgv_game_server_deployments.GameServerDeployment): + game_server_deployment (~.gcg_game_server_deployments.GameServerDeployment): Required. The game server delpoyment resource to be created. """ @@ -188,7 +188,7 @@ class UpdateGameServerDeploymentRequest(proto.Message): allows updates for labels. Attributes: - game_server_deployment (~.gcgv_game_server_deployments.GameServerDeployment): + game_server_deployment (~.gcg_game_server_deployments.GameServerDeployment): Required. The game server delpoyment to be updated. Only fields specified in update_mask are updated. update_mask (~.field_mask.FieldMask): @@ -212,7 +212,7 @@ class UpdateGameServerDeploymentRolloutRequest(proto.Message): GameServerDeploymentsService.UpdateGameServerRolloutDeployment. Attributes: - rollout (~.gcgv_game_server_deployments.GameServerDeploymentRollout): + rollout (~.gcg_game_server_deployments.GameServerDeploymentRollout): Required. The game server delpoyment rollout to be updated. Only fields specified in update_mask are updated. update_mask (~.field_mask.FieldMask): @@ -251,7 +251,7 @@ class FetchDeploymentStateResponse(proto.Message): GameServerDeploymentsService.FetchDeploymentState. Attributes: - cluster_state (Sequence[~.gcgv_game_server_deployments.FetchDeploymentStateResponse.DeployedClusterState]): + cluster_state (Sequence[~.gcg_game_server_deployments.FetchDeploymentStateResponse.DeployedClusterState]): The state of the game server deployment in each game server cluster. unavailable (Sequence[str]): @@ -293,13 +293,12 @@ class GameServerDeployment(proto.Message): ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``. For example, - - ``projects/my-project/locations/{location}/gameServerDeployments/my-deployment``. + ``projects/my-project/locations/global/gameServerDeployments/my-deployment``. create_time (~.timestamp.Timestamp): Output only. The creation time. update_time (~.timestamp.Timestamp): Output only. The last-modified time. - labels (Sequence[~.gcgv_game_server_deployments.GameServerDeployment.LabelsEntry]): + labels (Sequence[~.gcg_game_server_deployments.GameServerDeployment.LabelsEntry]): The labels associated with this game server deployment. Each label is a key-value pair. etag (str): @@ -351,7 +350,7 @@ class GameServerDeploymentRollout(proto.Message): ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout``. For example, - ``projects/my-project/locations/{location}/gameServerDeployments/my-deployment/rollout``. + ``projects/my-project/locations/global/gameServerDeployments/my-deployment/rollout``. create_time (~.timestamp.Timestamp): Output only. The creation time. update_time (~.timestamp.Timestamp): @@ -361,7 +360,7 @@ class GameServerDeploymentRollout(proto.Message): 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]): + game_server_config_overrides (Sequence[~.gcg_game_server_deployments.GameServerConfigOverride]): Contains the game server config rollout overrides. Overrides are processed in the order they are listed. Once a match is found for a @@ -389,7 +388,7 @@ class PreviewGameServerDeploymentRolloutRequest(proto.Message): r"""Request message for PreviewGameServerDeploymentRollout. Attributes: - rollout (~.gcgv_game_server_deployments.GameServerDeploymentRollout): + rollout (~.gcg_game_server_deployments.GameServerDeploymentRollout): Required. The game server deployment rollout to be updated. Only fields specified in update_mask are updated. update_mask (~.field_mask.FieldMask): 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 87138f5c..5b368610 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.v1", 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 78a54833..9133dcd9 100644 --- a/google/cloud/gaming_v1/types/realms.py +++ b/google/cloud/gaming_v1/types/realms.py @@ -24,7 +24,7 @@ __protobuf__ = proto.module( - package="google.cloud.gaming.v1beta", + package="google.cloud.gaming.v1", manifest={ "ListRealmsRequest", "ListRealmsResponse", @@ -51,7 +51,7 @@ class ListRealmsRequest(proto.Message): unspecified, server will pick an appropriate default. Server 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] + [next_page_token][google.cloud.gaming.v1.ListRealmsResponse.next_page_token] to determine if there are more realms left to be queried. page_token (str): Optional. The next_page_token value returned from a previous @@ -80,7 +80,7 @@ class ListRealmsResponse(proto.Message): r"""Response message for RealmsService.ListRealms. Attributes: - realms (Sequence[~.gcgv_realms.Realm]): + realms (Sequence[~.gcg_realms.Realm]): The list of realms. next_page_token (str): Token to retrieve the next page of results, @@ -123,7 +123,7 @@ class CreateRealmRequest(proto.Message): realm_id (str): Required. The ID of the realm resource to be created. - realm (~.gcgv_realms.Realm): + realm (~.gcg_realms.Realm): Required. The realm resource to be created. """ @@ -150,7 +150,7 @@ class UpdateRealmRequest(proto.Message): r"""Request message for RealmsService.UpdateRealm. Attributes: - realm (~.gcgv_realms.Realm): + realm (~.gcg_realms.Realm): Required. The realm to be updated. Only fields specified in update_mask are updated. update_mask (~.field_mask.FieldMask): @@ -170,7 +170,7 @@ class PreviewRealmUpdateRequest(proto.Message): r"""Request message for RealmsService.PreviewRealmUpdate. Attributes: - realm (~.gcgv_realms.Realm): + realm (~.gcg_realms.Realm): Required. The realm to be updated. Only fields specified in update_mask are updated. update_mask (~.field_mask.FieldMask): @@ -219,7 +219,7 @@ class Realm(proto.Message): Output only. The creation time. update_time (~.timestamp.Timestamp): Output only. The last-modified time. - labels (Sequence[~.gcgv_realms.Realm.LabelsEntry]): + labels (Sequence[~.gcg_realms.Realm.LabelsEntry]): The labels associated with this realm. Each label is a key-value pair. time_zone (str): diff --git a/google/cloud/gaming_v1/types/realms_service.py b/google/cloud/gaming_v1/types/realms_service.py index 87138f5c..5b368610 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.v1", manifest={},) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/__init__.py b/google/cloud/gaming_v1beta/__init__.py new file mode 100644 index 00000000..cddeaeec --- /dev/null +++ b/google/cloud/gaming_v1beta/__init__.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.game_server_clusters_service import GameServerClustersServiceClient +from .services.game_server_configs_service import GameServerConfigsServiceClient +from .services.game_server_deployments_service import GameServerDeploymentsServiceClient +from .services.realms_service import RealmsServiceClient +from .types.common import DeployedFleetDetails +from .types.common import LabelSelector +from .types.common import OperationMetadata +from .types.common import OperationStatus +from .types.common import RealmSelector +from .types.common import Schedule +from .types.common import SpecSource +from .types.common import TargetDetails +from .types.common import TargetState +from .types.game_server_clusters import CreateGameServerClusterRequest +from .types.game_server_clusters import DeleteGameServerClusterRequest +from .types.game_server_clusters import GameServerCluster +from .types.game_server_clusters import GameServerClusterConnectionInfo +from .types.game_server_clusters import GetGameServerClusterRequest +from .types.game_server_clusters import GkeClusterReference +from .types.game_server_clusters import ListGameServerClustersRequest +from .types.game_server_clusters import ListGameServerClustersResponse +from .types.game_server_clusters import PreviewCreateGameServerClusterRequest +from .types.game_server_clusters import PreviewCreateGameServerClusterResponse +from .types.game_server_clusters import PreviewDeleteGameServerClusterRequest +from .types.game_server_clusters import PreviewDeleteGameServerClusterResponse +from .types.game_server_clusters import PreviewUpdateGameServerClusterRequest +from .types.game_server_clusters import PreviewUpdateGameServerClusterResponse +from .types.game_server_clusters import UpdateGameServerClusterRequest +from .types.game_server_configs import CreateGameServerConfigRequest +from .types.game_server_configs import DeleteGameServerConfigRequest +from .types.game_server_configs import FleetConfig +from .types.game_server_configs import GameServerConfig +from .types.game_server_configs import GetGameServerConfigRequest +from .types.game_server_configs import ListGameServerConfigsRequest +from .types.game_server_configs import ListGameServerConfigsResponse +from .types.game_server_configs import ScalingConfig +from .types.game_server_deployments import CreateGameServerDeploymentRequest +from .types.game_server_deployments import DeleteGameServerDeploymentRequest +from .types.game_server_deployments import FetchDeploymentStateRequest +from .types.game_server_deployments import FetchDeploymentStateResponse +from .types.game_server_deployments import GameServerConfigOverride +from .types.game_server_deployments import GameServerDeployment +from .types.game_server_deployments import GameServerDeploymentRollout +from .types.game_server_deployments import GetGameServerDeploymentRequest +from .types.game_server_deployments import GetGameServerDeploymentRolloutRequest +from .types.game_server_deployments import ListGameServerDeploymentsRequest +from .types.game_server_deployments import ListGameServerDeploymentsResponse +from .types.game_server_deployments import PreviewGameServerDeploymentRolloutRequest +from .types.game_server_deployments import PreviewGameServerDeploymentRolloutResponse +from .types.game_server_deployments import UpdateGameServerDeploymentRequest +from .types.game_server_deployments import UpdateGameServerDeploymentRolloutRequest +from .types.realms import CreateRealmRequest +from .types.realms import DeleteRealmRequest +from .types.realms import GetRealmRequest +from .types.realms import ListRealmsRequest +from .types.realms import ListRealmsResponse +from .types.realms import PreviewRealmUpdateRequest +from .types.realms import PreviewRealmUpdateResponse +from .types.realms import Realm +from .types.realms import UpdateRealmRequest + + +__all__ = ( + "CreateGameServerClusterRequest", + "CreateGameServerConfigRequest", + "CreateGameServerDeploymentRequest", + "CreateRealmRequest", + "DeleteGameServerClusterRequest", + "DeleteGameServerConfigRequest", + "DeleteGameServerDeploymentRequest", + "DeleteRealmRequest", + "DeployedFleetDetails", + "FetchDeploymentStateRequest", + "FetchDeploymentStateResponse", + "FleetConfig", + "GameServerCluster", + "GameServerClusterConnectionInfo", + "GameServerClustersServiceClient", + "GameServerConfig", + "GameServerConfigOverride", + "GameServerConfigsServiceClient", + "GameServerDeployment", + "GameServerDeploymentRollout", + "GameServerDeploymentsServiceClient", + "GetGameServerClusterRequest", + "GetGameServerConfigRequest", + "GetGameServerDeploymentRequest", + "GetGameServerDeploymentRolloutRequest", + "GetRealmRequest", + "GkeClusterReference", + "LabelSelector", + "ListGameServerClustersRequest", + "ListGameServerClustersResponse", + "ListGameServerConfigsRequest", + "ListGameServerConfigsResponse", + "ListGameServerDeploymentsRequest", + "ListGameServerDeploymentsResponse", + "ListRealmsRequest", + "ListRealmsResponse", + "OperationMetadata", + "OperationStatus", + "PreviewCreateGameServerClusterRequest", + "PreviewCreateGameServerClusterResponse", + "PreviewDeleteGameServerClusterRequest", + "PreviewDeleteGameServerClusterResponse", + "PreviewGameServerDeploymentRolloutRequest", + "PreviewGameServerDeploymentRolloutResponse", + "PreviewRealmUpdateRequest", + "PreviewRealmUpdateResponse", + "PreviewUpdateGameServerClusterRequest", + "PreviewUpdateGameServerClusterResponse", + "Realm", + "RealmSelector", + "ScalingConfig", + "Schedule", + "SpecSource", + "TargetDetails", + "TargetState", + "UpdateGameServerClusterRequest", + "UpdateGameServerDeploymentRequest", + "UpdateGameServerDeploymentRolloutRequest", + "UpdateRealmRequest", + "RealmsServiceClient", +) diff --git a/google/cloud/gaming_v1beta/py.typed b/google/cloud/gaming_v1beta/py.typed new file mode 100644 index 00000000..0182f475 --- /dev/null +++ b/google/cloud/gaming_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gaming package uses inline types. diff --git a/google/cloud/gaming_v1beta/services/__init__.py b/google/cloud/gaming_v1beta/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/gaming_v1beta/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/google/cloud/gaming_v1beta/services/game_server_clusters_service/__init__.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/__init__.py new file mode 100644 index 00000000..965e452b --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import GameServerClustersServiceClient +from .async_client import GameServerClustersServiceAsyncClient + +__all__ = ( + "GameServerClustersServiceClient", + "GameServerClustersServiceAsyncClient", +) diff --git a/google/cloud/gaming_v1beta/services/game_server_clusters_service/async_client.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/async_client.py new file mode 100644 index 00000000..71dc21d9 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/async_client.py @@ -0,0 +1,755 @@ +# -*- 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_v1beta.services.game_server_clusters_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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=120.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_v1beta/services/game_server_clusters_service/client.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/client.py new file mode 100644 index 00000000..ac123342 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/client.py @@ -0,0 +1,903 @@ +# -*- 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 os +import re +from typing import Callable, 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.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_v1beta.services.game_server_clusters_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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): + """Metaclass for the GameServerClustersService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[GameServerClustersServiceTransport]] + _transport_registry["grpc"] = GameServerClustersServiceGrpcTransport + _transport_registry["grpc_asyncio"] = GameServerClustersServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[GameServerClustersServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class GameServerClustersServiceClient(metaclass=GameServerClustersServiceClientMeta): + """The game server cluster maps to Kubernetes clusters running + Agones and is used to manage fleets within clusters. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "gameservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def game_server_cluster_path( + 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, + ) + + @staticmethod + def parse_game_server_cluster_path(path: str) -> Dict[str, str]: + """Parse a game_server_cluster path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/realms/(?P.+?)/gameServerClusters/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, GameServerClustersServiceTransport] = None, + 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. + """ + 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 or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + 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.ListGameServerClustersPager: + 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.ListGameServerClustersPager: + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.ListGameServerClustersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.ListGameServerClustersRequest): + 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 = self._transport._wrapped_methods[ + self._transport.list_game_server_clusters + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGameServerClustersPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.GetGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.GetGameServerClusterRequest): + 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 = self._transport._wrapped_methods[self._transport.get_game_server_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_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.Operation: + 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.Operation: + 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. + has_flattened_params = any( + [parent, game_server_cluster, game_server_cluster_id] + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.CreateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.CreateGameServerClusterRequest): + 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 = self._transport._wrapped_methods[ + self._transport.create_game_server_cluster + ] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + game_server_clusters.GameServerCluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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. + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.PreviewCreateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_clusters.PreviewCreateGameServerClusterRequest + ): + request = game_server_clusters.PreviewCreateGameServerClusterRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.preview_create_game_server_cluster + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def 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.Operation: + 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.Operation: + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.DeleteGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.DeleteGameServerClusterRequest): + 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 = self._transport._wrapped_methods[ + self._transport.delete_game_server_cluster + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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. + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.PreviewDeleteGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_clusters.PreviewDeleteGameServerClusterRequest + ): + request = game_server_clusters.PreviewDeleteGameServerClusterRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.preview_delete_game_server_cluster + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_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.Operation: + 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.Operation: + 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. + has_flattened_params = any([game_server_cluster, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.UpdateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_clusters.UpdateGameServerClusterRequest): + 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 = self._transport._wrapped_methods[ + self._transport.update_game_server_cluster + ] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + game_server_clusters.GameServerCluster, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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. + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_clusters.PreviewUpdateGameServerClusterRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_clusters.PreviewUpdateGameServerClusterRequest + ): + request = game_server_clusters.PreviewUpdateGameServerClusterRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.preview_update_game_server_cluster + ] + + # 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,) + + # 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__ = ("GameServerClustersServiceClient",) diff --git a/google/cloud/gaming_v1beta/services/game_server_clusters_service/pagers.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/pagers.py new file mode 100644 index 00000000..9dbc6c32 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/pagers.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.gaming_v1beta.types import game_server_clusters + + +class ListGameServerClustersPager: + """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 ``__iter__`` method to iterate through its + ``game_server_clusters`` field. + + If there are more pages, the ``__iter__`` 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[..., 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 + 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, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[game_server_clusters.GameServerCluster]: + for page in self.pages: + yield from page.game_server_clusters + + 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_v1beta/services/game_server_clusters_service/transports/__init__.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/__init__.py new file mode 100644 index 00000000..ce769656 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import GameServerClustersServiceTransport +from .grpc import GameServerClustersServiceGrpcTransport +from .grpc_asyncio import GameServerClustersServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + 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_v1beta/services/game_server_clusters_service/transports/base.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/base.py new file mode 100644 index 00000000..d26a8cf9 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/base.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +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.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.gaming_v1beta.types import game_server_clusters +from google.longrunning import operations_pb2 as operations # type: ignore + + +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() + + +class GameServerClustersServiceTransport(abc.ABC): + """Abstract transport class for GameServerClustersService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + 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, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_game_server_clusters: gapic_v1.method.wrap_method( + self.list_game_server_clusters, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_cluster: gapic_v1.method.wrap_method( + self.get_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_game_server_cluster: gapic_v1.method.wrap_method( + self.create_game_server_cluster, + default_timeout=120.0, + client_info=_client_info, + ), + self.preview_create_game_server_cluster: gapic_v1.method.wrap_method( + self.preview_create_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_game_server_cluster: gapic_v1.method.wrap_method( + self.delete_game_server_cluster, + default_timeout=60.0, + client_info=_client_info, + ), + self.preview_delete_game_server_cluster: gapic_v1.method.wrap_method( + self.preview_delete_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_game_server_cluster: gapic_v1.method.wrap_method( + self.update_game_server_cluster, + default_timeout=60.0, + client_info=_client_info, + ), + self.preview_update_game_server_cluster: gapic_v1.method.wrap_method( + self.preview_update_game_server_cluster, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_game_server_clusters( + self, + ) -> typing.Callable[ + [game_server_clusters.ListGameServerClustersRequest], + typing.Union[ + game_server_clusters.ListGameServerClustersResponse, + typing.Awaitable[game_server_clusters.ListGameServerClustersResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_game_server_cluster( + self, + ) -> typing.Callable[ + [game_server_clusters.GetGameServerClusterRequest], + typing.Union[ + game_server_clusters.GameServerCluster, + typing.Awaitable[game_server_clusters.GameServerCluster], + ], + ]: + raise NotImplementedError() + + @property + def create_game_server_cluster( + self, + ) -> typing.Callable[ + [game_server_clusters.CreateGameServerClusterRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def preview_create_game_server_cluster( + self, + ) -> typing.Callable[ + [game_server_clusters.PreviewCreateGameServerClusterRequest], + typing.Union[ + game_server_clusters.PreviewCreateGameServerClusterResponse, + typing.Awaitable[ + game_server_clusters.PreviewCreateGameServerClusterResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def delete_game_server_cluster( + self, + ) -> typing.Callable[ + [game_server_clusters.DeleteGameServerClusterRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def preview_delete_game_server_cluster( + self, + ) -> typing.Callable[ + [game_server_clusters.PreviewDeleteGameServerClusterRequest], + typing.Union[ + game_server_clusters.PreviewDeleteGameServerClusterResponse, + typing.Awaitable[ + game_server_clusters.PreviewDeleteGameServerClusterResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def update_game_server_cluster( + self, + ) -> typing.Callable[ + [game_server_clusters.UpdateGameServerClusterRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def preview_update_game_server_cluster( + self, + ) -> typing.Callable[ + [game_server_clusters.PreviewUpdateGameServerClusterRequest], + typing.Union[ + game_server_clusters.PreviewUpdateGameServerClusterResponse, + typing.Awaitable[ + game_server_clusters.PreviewUpdateGameServerClusterResponse + ], + ], + ]: + raise NotImplementedError() + + +__all__ = ("GameServerClustersServiceTransport",) diff --git a/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/grpc.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/grpc.py new file mode 100644 index 00000000..9de033f8 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/grpc.py @@ -0,0 +1,467 @@ +# -*- 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 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 + + +import grpc # type: ignore + +from google.cloud.gaming_v1beta.types import game_server_clusters +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import GameServerClustersServiceTransport + + +class GameServerClustersServiceGrpcTransport(GameServerClustersServiceTransport): + """gRPC 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. + """ + + _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, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.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.OperationsClient: + """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.OperationsClient( + 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], + 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], + ~.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], + 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], + ~.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], 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], + ~.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], + 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], + ~.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], operations.Operation + ]: + r"""Return a callable for the delete game server cluster method over gRPC. + + Deletes a single game server cluster. + + Returns: + Callable[[~.DeleteGameServerClusterRequest], + ~.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], + 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], + ~.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], operations.Operation + ]: + r"""Return a callable for the update game server cluster method over gRPC. + + Patches a single game server cluster. + + Returns: + Callable[[~.UpdateGameServerClusterRequest], + ~.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], + 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], + ~.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__ = ("GameServerClustersServiceGrpcTransport",) diff --git a/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..35c2600c --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_clusters_service/transports/grpc_asyncio.py @@ -0,0 +1,463 @@ +# -*- 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_v1beta.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, + quota_project_id: Optional[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`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **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, + quota_project_id=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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + 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_v1beta/services/game_server_configs_service/__init__.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/__init__.py new file mode 100644 index 00000000..a805cae2 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import GameServerConfigsServiceClient +from .async_client import GameServerConfigsServiceAsyncClient + +__all__ = ( + "GameServerConfigsServiceClient", + "GameServerConfigsServiceAsyncClient", +) diff --git a/google/cloud/gaming_v1beta/services/game_server_configs_service/async_client.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/async_client.py new file mode 100644 index 00000000..1aadee07 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/async_client.py @@ -0,0 +1,477 @@ +# -*- 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_v1beta.services.game_server_configs_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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=60.0, + 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=60.0, + 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_v1beta/services/game_server_configs_service/client.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/client.py new file mode 100644 index 00000000..19ae568d --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/client.py @@ -0,0 +1,618 @@ +# -*- 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 os +import re +from typing import Callable, 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.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_v1beta.services.game_server_configs_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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): + """Metaclass for the GameServerConfigsService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[GameServerConfigsServiceTransport]] + _transport_registry["grpc"] = GameServerConfigsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = GameServerConfigsServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[GameServerConfigsServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class GameServerConfigsServiceClient(metaclass=GameServerConfigsServiceClientMeta): + """The game server config configures the game servers in an + Agones fleet. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "gameservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def game_server_config_path( + 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, + ) + + @staticmethod + def parse_game_server_config_path(path: str) -> Dict[str, str]: + """Parse a game_server_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/gameServerDeployments/(?P.+?)/configs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, GameServerConfigsServiceTransport] = None, + 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. + """ + 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 or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + 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.ListGameServerConfigsPager: + 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.ListGameServerConfigsPager: + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.ListGameServerConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.ListGameServerConfigsRequest): + 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 = self._transport._wrapped_methods[self._transport.list_game_server_configs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGameServerConfigsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.GetGameServerConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.GetGameServerConfigRequest): + 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 = self._transport._wrapped_methods[self._transport.get_game_server_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_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.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 + 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.Operation: + 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. + has_flattened_params = any([parent, game_server_config]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.CreateGameServerConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.CreateGameServerConfigRequest): + 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 = self._transport._wrapped_methods[ + self._transport.create_game_server_config + ] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + game_server_configs.GameServerConfig, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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.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. + + 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.Operation: + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_configs.DeleteGameServerConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_configs.DeleteGameServerConfigRequest): + 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 = self._transport._wrapped_methods[ + self._transport.delete_game_server_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + 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__ = ("GameServerConfigsServiceClient",) diff --git a/google/cloud/gaming_v1beta/services/game_server_configs_service/pagers.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/pagers.py new file mode 100644 index 00000000..60fb386c --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/pagers.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.gaming_v1beta.types import game_server_configs + + +class ListGameServerConfigsPager: + """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 ``__iter__`` method to iterate through its + ``game_server_configs`` field. + + If there are more pages, the ``__iter__`` 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[..., 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 + 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, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[game_server_configs.GameServerConfig]: + for page in self.pages: + yield from page.game_server_configs + + 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_v1beta/services/game_server_configs_service/transports/__init__.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/__init__.py new file mode 100644 index 00000000..5aa419a6 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import GameServerConfigsServiceTransport +from .grpc import GameServerConfigsServiceGrpcTransport +from .grpc_asyncio import GameServerConfigsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[GameServerConfigsServiceTransport]] +_transport_registry["grpc"] = GameServerConfigsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = GameServerConfigsServiceGrpcAsyncIOTransport + + +__all__ = ( + "GameServerConfigsServiceTransport", + "GameServerConfigsServiceGrpcTransport", + "GameServerConfigsServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/base.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/base.py new file mode 100644 index 00000000..0218abd2 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/base.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +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.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.gaming_v1beta.types import game_server_configs +from google.longrunning import operations_pb2 as operations # type: ignore + + +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() + + +class GameServerConfigsServiceTransport(abc.ABC): + """Abstract transport class for GameServerConfigsService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + 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, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_game_server_configs: gapic_v1.method.wrap_method( + self.list_game_server_configs, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_config: gapic_v1.method.wrap_method( + self.get_game_server_config, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_game_server_config: gapic_v1.method.wrap_method( + self.create_game_server_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_game_server_config: gapic_v1.method.wrap_method( + self.delete_game_server_config, + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_game_server_configs( + self, + ) -> typing.Callable[ + [game_server_configs.ListGameServerConfigsRequest], + typing.Union[ + game_server_configs.ListGameServerConfigsResponse, + typing.Awaitable[game_server_configs.ListGameServerConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_game_server_config( + self, + ) -> typing.Callable[ + [game_server_configs.GetGameServerConfigRequest], + typing.Union[ + game_server_configs.GameServerConfig, + typing.Awaitable[game_server_configs.GameServerConfig], + ], + ]: + raise NotImplementedError() + + @property + def create_game_server_config( + self, + ) -> typing.Callable[ + [game_server_configs.CreateGameServerConfigRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_game_server_config( + self, + ) -> typing.Callable[ + [game_server_configs.DeleteGameServerConfigRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("GameServerConfigsServiceTransport",) diff --git a/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/grpc.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/grpc.py new file mode 100644 index 00000000..112c69cd --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/grpc.py @@ -0,0 +1,347 @@ +# -*- 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 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 + + +import grpc # type: ignore + +from google.cloud.gaming_v1beta.types import game_server_configs +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import GameServerConfigsServiceTransport + + +class GameServerConfigsServiceGrpcTransport(GameServerConfigsServiceTransport): + """gRPC 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. + """ + + _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, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.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.OperationsClient: + """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.OperationsClient( + 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], + 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], + ~.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], + 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], + ~.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], 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], + ~.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], 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], + ~.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__ = ("GameServerConfigsServiceGrpcTransport",) diff --git a/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2fb0f59a --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_configs_service/transports/grpc_asyncio.py @@ -0,0 +1,342 @@ +# -*- 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_v1beta.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, + quota_project_id: Optional[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`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **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, + quota_project_id=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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + 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_v1beta/services/game_server_deployments_service/__init__.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/__init__.py new file mode 100644 index 00000000..b24578bc --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import GameServerDeploymentsServiceClient +from .async_client import GameServerDeploymentsServiceAsyncClient + +__all__ = ( + "GameServerDeploymentsServiceClient", + "GameServerDeploymentsServiceAsyncClient", +) diff --git a/google/cloud/gaming_v1beta/services/game_server_deployments_service/async_client.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/async_client.py new file mode 100644 index 00000000..30f9ffc9 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/async_client.py @@ -0,0 +1,885 @@ +# -*- 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_v1beta.services.game_server_deployments_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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_rollout_path = staticmethod( + GameServerDeploymentsServiceClient.game_server_deployment_rollout_path + ) + + game_server_deployment_path = staticmethod( + GameServerDeploymentsServiceClient.game_server_deployment_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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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=60.0, + 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=60.0, + 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=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_v1beta/services/game_server_deployments_service/client.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/client.py new file mode 100644 index 00000000..085b4f48 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/client.py @@ -0,0 +1,1062 @@ +# -*- 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 os +import re +from typing import Callable, 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.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_v1beta.services.game_server_deployments_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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): + """Metaclass for the GameServerDeploymentsService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[GameServerDeploymentsServiceTransport]] + _transport_registry["grpc"] = GameServerDeploymentsServiceGrpcTransport + _transport_registry[ + "grpc_asyncio" + ] = GameServerDeploymentsServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[GameServerDeploymentsServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class GameServerDeploymentsServiceClient( + metaclass=GameServerDeploymentsServiceClientMeta +): + """The game server deployment is used to control the deployment + of Agones fleets. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "gameservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def game_server_deployment_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, + ) + + @staticmethod + 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.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def game_server_deployment_rollout_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, + ) + + @staticmethod + 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.+?)/rollout$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, GameServerDeploymentsServiceTransport] = None, + 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. + """ + 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 or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + 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.ListGameServerDeploymentsPager: + 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.ListGameServerDeploymentsPager: + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.ListGameServerDeploymentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.ListGameServerDeploymentsRequest + ): + 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 = self._transport._wrapped_methods[ + self._transport.list_game_server_deployments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGameServerDeploymentsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.GetGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.GetGameServerDeploymentRequest + ): + 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 = self._transport._wrapped_methods[ + self._transport.get_game_server_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_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.Operation: + 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.Operation: + 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. + has_flattened_params = any([parent, game_server_deployment]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.CreateGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.CreateGameServerDeploymentRequest + ): + 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 = self._transport._wrapped_methods[ + self._transport.create_game_server_deployment + ] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + game_server_deployments.GameServerDeployment, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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.Operation: + 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.Operation: + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.DeleteGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.DeleteGameServerDeploymentRequest + ): + 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 = self._transport._wrapped_methods[ + self._transport.delete_game_server_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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.Operation: + 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.Operation: + 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. + has_flattened_params = any([game_server_deployment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.UpdateGameServerDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.UpdateGameServerDeploymentRequest + ): + 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 = self._transport._wrapped_methods[ + self._transport.update_game_server_deployment + ] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + game_server_deployments.GameServerDeployment, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.GetGameServerDeploymentRolloutRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.GetGameServerDeploymentRolloutRequest + ): + 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 = self._transport._wrapped_methods[ + self._transport.get_game_server_deployment_rollout + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_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.Operation: + 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.Operation: + 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. + has_flattened_params = any([rollout, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.UpdateGameServerDeploymentRolloutRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.UpdateGameServerDeploymentRolloutRequest + ): + 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 = self._transport._wrapped_methods[ + self._transport.update_game_server_deployment_rollout + ] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + game_server_deployments.GameServerDeployment, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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. + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.PreviewGameServerDeploymentRolloutRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, game_server_deployments.PreviewGameServerDeploymentRolloutRequest + ): + request = game_server_deployments.PreviewGameServerDeploymentRolloutRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.preview_game_server_deployment_rollout + ] + + # 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,) + + # Done; return the response. + return response + + 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. + + # Minor optimization to avoid making a copy if the user passes + # in a game_server_deployments.FetchDeploymentStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, game_server_deployments.FetchDeploymentStateRequest): + request = game_server_deployments.FetchDeploymentStateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_deployment_state] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _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__ = ("GameServerDeploymentsServiceClient",) diff --git a/google/cloud/gaming_v1beta/services/game_server_deployments_service/pagers.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/pagers.py new file mode 100644 index 00000000..c3ca0a87 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/pagers.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.gaming_v1beta.types import game_server_deployments + + +class ListGameServerDeploymentsPager: + """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 ``__iter__`` method to iterate through its + ``game_server_deployments`` field. + + If there are more pages, the ``__iter__`` 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[ + ..., 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 + def pages( + 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, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[game_server_deployments.GameServerDeployment]: + for page in self.pages: + yield from page.game_server_deployments + + 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_v1beta/services/game_server_deployments_service/transports/__init__.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/__init__.py new file mode 100644 index 00000000..17e99cc0 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import GameServerDeploymentsServiceTransport +from .grpc import GameServerDeploymentsServiceGrpcTransport +from .grpc_asyncio import GameServerDeploymentsServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + 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_v1beta/services/game_server_deployments_service/transports/base.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/base.py new file mode 100644 index 00000000..382bb205 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/base.py @@ -0,0 +1,286 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +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.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.gaming_v1beta.types import game_server_deployments +from google.longrunning import operations_pb2 as operations # type: ignore + + +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() + + +class GameServerDeploymentsServiceTransport(abc.ABC): + """Abstract transport class for GameServerDeploymentsService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + 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, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_game_server_deployments: gapic_v1.method.wrap_method( + self.list_game_server_deployments, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_deployment: gapic_v1.method.wrap_method( + self.get_game_server_deployment, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_game_server_deployment: gapic_v1.method.wrap_method( + self.create_game_server_deployment, + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_game_server_deployment: gapic_v1.method.wrap_method( + self.delete_game_server_deployment, + default_timeout=60.0, + client_info=_client_info, + ), + self.update_game_server_deployment: gapic_v1.method.wrap_method( + self.update_game_server_deployment, + default_timeout=60.0, + client_info=_client_info, + ), + self.get_game_server_deployment_rollout: gapic_v1.method.wrap_method( + self.get_game_server_deployment_rollout, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_game_server_deployment_rollout: gapic_v1.method.wrap_method( + self.update_game_server_deployment_rollout, + default_timeout=60.0, + client_info=_client_info, + ), + self.preview_game_server_deployment_rollout: gapic_v1.method.wrap_method( + self.preview_game_server_deployment_rollout, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.fetch_deployment_state: gapic_v1.method.wrap_method( + self.fetch_deployment_state, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_game_server_deployments( + self, + ) -> typing.Callable[ + [game_server_deployments.ListGameServerDeploymentsRequest], + typing.Union[ + game_server_deployments.ListGameServerDeploymentsResponse, + typing.Awaitable[game_server_deployments.ListGameServerDeploymentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_game_server_deployment( + self, + ) -> typing.Callable[ + [game_server_deployments.GetGameServerDeploymentRequest], + typing.Union[ + game_server_deployments.GameServerDeployment, + typing.Awaitable[game_server_deployments.GameServerDeployment], + ], + ]: + raise NotImplementedError() + + @property + def create_game_server_deployment( + self, + ) -> typing.Callable[ + [game_server_deployments.CreateGameServerDeploymentRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_game_server_deployment( + self, + ) -> typing.Callable[ + [game_server_deployments.DeleteGameServerDeploymentRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def update_game_server_deployment( + self, + ) -> typing.Callable[ + [game_server_deployments.UpdateGameServerDeploymentRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def get_game_server_deployment_rollout( + self, + ) -> typing.Callable[ + [game_server_deployments.GetGameServerDeploymentRolloutRequest], + typing.Union[ + game_server_deployments.GameServerDeploymentRollout, + typing.Awaitable[game_server_deployments.GameServerDeploymentRollout], + ], + ]: + raise NotImplementedError() + + @property + def update_game_server_deployment_rollout( + self, + ) -> typing.Callable[ + [game_server_deployments.UpdateGameServerDeploymentRolloutRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def preview_game_server_deployment_rollout( + self, + ) -> typing.Callable[ + [game_server_deployments.PreviewGameServerDeploymentRolloutRequest], + typing.Union[ + game_server_deployments.PreviewGameServerDeploymentRolloutResponse, + typing.Awaitable[ + game_server_deployments.PreviewGameServerDeploymentRolloutResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def fetch_deployment_state( + self, + ) -> typing.Callable[ + [game_server_deployments.FetchDeploymentStateRequest], + typing.Union[ + game_server_deployments.FetchDeploymentStateResponse, + typing.Awaitable[game_server_deployments.FetchDeploymentStateResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("GameServerDeploymentsServiceTransport",) diff --git a/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/grpc.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/grpc.py new file mode 100644 index 00000000..77a2c611 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/grpc.py @@ -0,0 +1,514 @@ +# -*- 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 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 + + +import grpc # type: ignore + +from google.cloud.gaming_v1beta.types import game_server_deployments +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import GameServerDeploymentsServiceTransport + + +class GameServerDeploymentsServiceGrpcTransport(GameServerDeploymentsServiceTransport): + """gRPC 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. + """ + + _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, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.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.OperationsClient: + """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.OperationsClient( + 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], + 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], + ~.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], + 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], + ~.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], + 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], + ~.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], + operations.Operation, + ]: + r"""Return a callable for the delete game server deployment method over gRPC. + + Deletes a single game server deployment. + + Returns: + Callable[[~.DeleteGameServerDeploymentRequest], + ~.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], + operations.Operation, + ]: + r"""Return a callable for the update game server deployment method over gRPC. + + Patches a game server deployment. + + Returns: + Callable[[~.UpdateGameServerDeploymentRequest], + ~.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], + 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], + ~.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], + 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], + ~.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], + 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], + ~.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], + 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], + ~.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__ = ("GameServerDeploymentsServiceGrpcTransport",) diff --git a/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..afdcdc54 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/game_server_deployments_service/transports/grpc_asyncio.py @@ -0,0 +1,509 @@ +# -*- 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_v1beta.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, + quota_project_id: Optional[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`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **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, + quota_project_id=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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + 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_v1beta/services/realms_service/__init__.py b/google/cloud/gaming_v1beta/services/realms_service/__init__.py new file mode 100644 index 00000000..bef41506 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import RealmsServiceClient +from .async_client import RealmsServiceAsyncClient + +__all__ = ( + "RealmsServiceClient", + "RealmsServiceAsyncClient", +) diff --git a/google/cloud/gaming_v1beta/services/realms_service/async_client.py b/google/cloud/gaming_v1beta/services/realms_service/async_client.py new file mode 100644 index 00000000..22639b9b --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/async_client.py @@ -0,0 +1,626 @@ +# -*- 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_v1beta.services.realms_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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=60.0, + 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=60.0, + 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=60.0, + 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_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + 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_v1beta/services/realms_service/client.py b/google/cloud/gaming_v1beta/services/realms_service/client.py new file mode 100644 index 00000000..83cf35aa --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/client.py @@ -0,0 +1,757 @@ +# -*- 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 os +import re +from typing import Callable, 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.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_v1beta.services.realms_service import pagers +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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): + """Metaclass for the RealmsService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[RealmsServiceTransport]] + _transport_registry["grpc"] = RealmsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RealmsServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[RealmsServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RealmsServiceClient(metaclass=RealmsServiceClientMeta): + """A realm is a grouping of game server clusters that are + considered interchangeable. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "gameservices.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + 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, + ) + + @staticmethod + def parse_realm_path(path: str) -> Dict[str, str]: + """Parse a realm path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/realms/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, RealmsServiceTransport] = None, + 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. + """ + 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 or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + 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.ListRealmsPager: + 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.ListRealmsPager: + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a realms.ListRealmsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.ListRealmsRequest): + 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 = self._transport._wrapped_methods[self._transport.list_realms] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRealmsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a realms.GetRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.GetRealmRequest): + 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 = self._transport._wrapped_methods[self._transport.get_realm] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_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.Operation: + 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.Operation: + 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. + has_flattened_params = any([parent, realm, realm_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a realms.CreateRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.CreateRealmRequest): + 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 = self._transport._wrapped_methods[self._transport.create_realm] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + realms.Realm, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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.Operation: + 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.Operation: + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a realms.DeleteRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.DeleteRealmRequest): + 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 = self._transport._wrapped_methods[self._transport.delete_realm] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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.Operation: + 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.Operation: + 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. + has_flattened_params = any([realm, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a realms.UpdateRealmRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.UpdateRealmRequest): + 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 = self._transport._wrapped_methods[self._transport.update_realm] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + realms.Realm, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + 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. + + # Minor optimization to avoid making a copy if the user passes + # in a realms.PreviewRealmUpdateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, realms.PreviewRealmUpdateRequest): + request = realms.PreviewRealmUpdateRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.preview_realm_update] + + # 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,) + + # 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__ = ("RealmsServiceClient",) diff --git a/google/cloud/gaming_v1beta/services/realms_service/pagers.py b/google/cloud/gaming_v1beta/services/realms_service/pagers.py new file mode 100644 index 00000000..e3ab4306 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/pagers.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.gaming_v1beta.types import realms + + +class ListRealmsPager: + """A pager for iterating through ``list_realms`` requests. + + This class thinly wraps an initial + :class:`~.realms.ListRealmsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``realms`` field. + + If there are more pages, the ``__iter__`` 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[..., 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 + 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, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[realms.Realm]: + for page in self.pages: + yield from page.realms + + 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_v1beta/services/realms_service/transports/__init__.py b/google/cloud/gaming_v1beta/services/realms_service/transports/__init__.py new file mode 100644 index 00000000..2b139b78 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import 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", + "RealmsServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/gaming_v1beta/services/realms_service/transports/base.py b/google/cloud/gaming_v1beta/services/realms_service/transports/base.py new file mode 100644 index 00000000..ab96aab3 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/transports/base.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth +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.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.gaming_v1beta.types import realms +from google.longrunning import operations_pb2 as operations # type: ignore + + +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() + + +class RealmsServiceTransport(abc.ABC): + """Abstract transport class for RealmsService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + 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, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_realms: gapic_v1.method.wrap_method( + self.list_realms, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_realm: gapic_v1.method.wrap_method( + self.get_realm, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_realm: gapic_v1.method.wrap_method( + self.create_realm, default_timeout=60.0, client_info=_client_info, + ), + self.delete_realm: gapic_v1.method.wrap_method( + self.delete_realm, default_timeout=60.0, client_info=_client_info, + ), + self.update_realm: gapic_v1.method.wrap_method( + self.update_realm, default_timeout=60.0, client_info=_client_info, + ), + self.preview_realm_update: gapic_v1.method.wrap_method( + self.preview_realm_update, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_realms( + self, + ) -> typing.Callable[ + [realms.ListRealmsRequest], + typing.Union[ + realms.ListRealmsResponse, typing.Awaitable[realms.ListRealmsResponse] + ], + ]: + raise NotImplementedError() + + @property + 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], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_realm( + self, + ) -> typing.Callable[ + [realms.DeleteRealmRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def update_realm( + self, + ) -> typing.Callable[ + [realms.UpdateRealmRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def preview_realm_update( + self, + ) -> typing.Callable[ + [realms.PreviewRealmUpdateRequest], + typing.Union[ + realms.PreviewRealmUpdateResponse, + typing.Awaitable[realms.PreviewRealmUpdateResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("RealmsServiceTransport",) diff --git a/google/cloud/gaming_v1beta/services/realms_service/transports/grpc.py b/google/cloud/gaming_v1beta/services/realms_service/transports/grpc.py new file mode 100644 index 00000000..fdfc9459 --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/transports/grpc.py @@ -0,0 +1,382 @@ +# -*- 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 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 + + +import grpc # type: ignore + +from google.cloud.gaming_v1beta.types import realms +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import RealmsServiceTransport + + +class RealmsServiceGrpcTransport(RealmsServiceTransport): + """gRPC 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. + """ + + _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, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # 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, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "gameservices.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.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.OperationsClient: + """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.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def list_realms( + 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. + + Returns: + Callable[[~.ListRealmsRequest], + ~.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], realms.Realm]: + r"""Return a callable for the get realm method over gRPC. + + Gets details of a single realm. + + Returns: + Callable[[~.GetRealmRequest], + ~.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], 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], + ~.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], operations.Operation]: + r"""Return a callable for the delete realm method over gRPC. + + Deletes a single realm. + + Returns: + Callable[[~.DeleteRealmRequest], + ~.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], operations.Operation]: + r"""Return a callable for the update realm method over gRPC. + + Patches a single realm. + + Returns: + Callable[[~.UpdateRealmRequest], + ~.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], realms.PreviewRealmUpdateResponse + ]: + r"""Return a callable for the preview realm update method over gRPC. + + Previews patches to a single realm. + + Returns: + Callable[[~.PreviewRealmUpdateRequest], + ~.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__ = ("RealmsServiceGrpcTransport",) diff --git a/google/cloud/gaming_v1beta/services/realms_service/transports/grpc_asyncio.py b/google/cloud/gaming_v1beta/services/realms_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..a287ddeb --- /dev/null +++ b/google/cloud/gaming_v1beta/services/realms_service/transports/grpc_asyncio.py @@ -0,0 +1,375 @@ +# -*- 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_v1beta.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, + quota_project_id: Optional[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`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **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, + quota_project_id=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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + 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_v1beta/types/__init__.py b/google/cloud/gaming_v1beta/types/__init__.py new file mode 100644 index 00000000..fea9d663 --- /dev/null +++ b/google/cloud/gaming_v1beta/types/__init__.py @@ -0,0 +1,143 @@ +# -*- 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 .common import ( + OperationMetadata, + OperationStatus, + LabelSelector, + RealmSelector, + Schedule, + SpecSource, + TargetDetails, + TargetState, + DeployedFleetDetails, +) +from .game_server_clusters import ( + ListGameServerClustersRequest, + ListGameServerClustersResponse, + GetGameServerClusterRequest, + CreateGameServerClusterRequest, + PreviewCreateGameServerClusterRequest, + PreviewCreateGameServerClusterResponse, + DeleteGameServerClusterRequest, + PreviewDeleteGameServerClusterRequest, + PreviewDeleteGameServerClusterResponse, + UpdateGameServerClusterRequest, + PreviewUpdateGameServerClusterRequest, + PreviewUpdateGameServerClusterResponse, + GameServerClusterConnectionInfo, + GkeClusterReference, + GameServerCluster, +) +from .game_server_configs import ( + ListGameServerConfigsRequest, + ListGameServerConfigsResponse, + GetGameServerConfigRequest, + CreateGameServerConfigRequest, + DeleteGameServerConfigRequest, + ScalingConfig, + 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, + GetRealmRequest, + CreateRealmRequest, + DeleteRealmRequest, + UpdateRealmRequest, + PreviewRealmUpdateRequest, + PreviewRealmUpdateResponse, + Realm, +) + + +__all__ = ( + "OperationMetadata", + "OperationStatus", + "LabelSelector", + "RealmSelector", + "Schedule", + "SpecSource", + "TargetDetails", + "TargetState", + "DeployedFleetDetails", + "ListGameServerClustersRequest", + "ListGameServerClustersResponse", + "GetGameServerClusterRequest", + "CreateGameServerClusterRequest", + "PreviewCreateGameServerClusterRequest", + "PreviewCreateGameServerClusterResponse", + "DeleteGameServerClusterRequest", + "PreviewDeleteGameServerClusterRequest", + "PreviewDeleteGameServerClusterResponse", + "UpdateGameServerClusterRequest", + "PreviewUpdateGameServerClusterRequest", + "PreviewUpdateGameServerClusterResponse", + "GameServerClusterConnectionInfo", + "GkeClusterReference", + "GameServerCluster", + "ListGameServerConfigsRequest", + "ListGameServerConfigsResponse", + "GetGameServerConfigRequest", + "CreateGameServerConfigRequest", + "DeleteGameServerConfigRequest", + "ScalingConfig", + "FleetConfig", + "GameServerConfig", + "ListGameServerDeploymentsRequest", + "ListGameServerDeploymentsResponse", + "GetGameServerDeploymentRequest", + "GetGameServerDeploymentRolloutRequest", + "CreateGameServerDeploymentRequest", + "DeleteGameServerDeploymentRequest", + "UpdateGameServerDeploymentRequest", + "UpdateGameServerDeploymentRolloutRequest", + "FetchDeploymentStateRequest", + "FetchDeploymentStateResponse", + "GameServerDeployment", + "GameServerConfigOverride", + "GameServerDeploymentRollout", + "PreviewGameServerDeploymentRolloutRequest", + "PreviewGameServerDeploymentRolloutResponse", + "ListRealmsRequest", + "ListRealmsResponse", + "GetRealmRequest", + "CreateRealmRequest", + "DeleteRealmRequest", + "UpdateRealmRequest", + "PreviewRealmUpdateRequest", + "PreviewRealmUpdateResponse", + "Realm", +) diff --git a/google/cloud/gaming_v1beta/types/common.py b/google/cloud/gaming_v1beta/types/common.py new file mode 100644 index 00000000..839ca1d7 --- /dev/null +++ b/google/cloud/gaming_v1beta/types/common.py @@ -0,0 +1,398 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.gaming.v1beta", + manifest={ + "OperationMetadata", + "OperationStatus", + "LabelSelector", + "RealmSelector", + "Schedule", + "SpecSource", + "TargetDetails", + "TargetState", + "DeployedFleetDetails", + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (~.timestamp.Timestamp): + Output only. The time the operation was + created. + end_time (~.timestamp.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + unreachable (Sequence[str]): + Output only. List of Locations that could not + be reached. + operation_status (Sequence[~.common.OperationMetadata.OperationStatusEntry]): + 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,) + + 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", + ) + + +class OperationStatus(proto.Message): + r""" + + Attributes: + done (bool): + Output only. Whether the operation is done or + still in progress. + error_code (~.common.OperationStatus.ErrorCode): + The error code in case of failures. + error_message (str): + The human-readable error message. + """ + + class ErrorCode(proto.Enum): + r"""""" + ERROR_CODE_UNSPECIFIED = 0 + INTERNAL_ERROR = 1 + PERMISSION_DENIED = 2 + CLUSTER_CONNECTION = 3 + + done = proto.Field(proto.BOOL, number=1) + + error_code = proto.Field(proto.ENUM, number=2, enum=ErrorCode,) + + error_message = proto.Field(proto.STRING, number=3) + + +class LabelSelector(proto.Message): + r"""The label selector, used to group labels on the resources. + + Attributes: + labels (Sequence[~.common.LabelSelector.LabelsEntry]): + Resource labels for this selector. + """ + + labels = proto.MapField(proto.STRING, proto.STRING, number=1) + + +class RealmSelector(proto.Message): + r"""The realm selector, used to match realm resources. + + Attributes: + realms (Sequence[str]): + List of realms to match. + """ + + realms = proto.RepeatedField(proto.STRING, number=1) + + +class Schedule(proto.Message): + r"""The schedule of a recurring or one time event. The event's time span + is specified by start_time and end_time. If the scheduled event's + timespan is larger than the cron_spec + cron_job_duration, the event + will be recurring. If only cron_spec + cron_job_duration are + specified, the event is effective starting at the local time + specified by cron_spec, and is recurring. + + :: + + start_time|-------[cron job]-------[cron job]-------[cron job]---|end_time + cron job: cron spec start time + duration + + + Attributes: + start_time (~.timestamp.Timestamp): + The start time of the event. + end_time (~.timestamp.Timestamp): + The end time of the event. + cron_job_duration (~.duration.Duration): + The duration for the cron job event. The + duration of the event is effective after the + cron job's start time. + cron_spec (str): + 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. + """ + + 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) + + +class SpecSource(proto.Message): + r"""Encapsulates Agones fleet spec and Agones autoscaler spec + sources. + + Attributes: + game_server_config_name (str): + The game server config resource. Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}/configs/{config_id}``. + name (str): + The name of the Agones leet config or Agones + scaling config used to derive the Agones fleet + or Agones autoscaler spec. + """ + + game_server_config_name = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=2) + + +class TargetDetails(proto.Message): + r"""Details about the Agones resources. + + Attributes: + game_server_cluster_name (str): + 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: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment_id}``. + fleet_details (Sequence[~.common.TargetDetails.TargetFleetDetails]): + Agones fleet details for game server clusters + and game server deployments. + """ + + class TargetFleetDetails(proto.Message): + r"""Details of the target Agones fleet. + + Attributes: + fleet (~.common.TargetDetails.TargetFleetDetails.TargetFleet): + Reference to target Agones fleet. + autoscaler (~.common.TargetDetails.TargetFleetDetails.TargetFleetAutoscaler): + Reference to target Agones fleet autoscaling + policy. + """ + + class TargetFleet(proto.Message): + r"""Target Agones fleet specification. + + Attributes: + name (str): + The name of the Agones fleet. + spec_source (~.common.SpecSource): + Encapsulates the source of the Agones fleet + spec. The Agones fleet spec source. + """ + + name = proto.Field(proto.STRING, number=1) + + spec_source = proto.Field(proto.MESSAGE, number=2, message=SpecSource,) + + class TargetFleetAutoscaler(proto.Message): + r"""Target Agones autoscaler policy reference. + + Attributes: + name (str): + The name of the Agones autoscaler. + spec_source (~.common.SpecSource): + Encapsulates the source of the Agones fleet + spec. Details about the Agones autoscaler spec. + """ + + name = proto.Field(proto.STRING, number=1) + + 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, + message="TargetDetails.TargetFleetDetails.TargetFleetAutoscaler", + ) + + 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, + ) + + +class TargetState(proto.Message): + r"""Encapsulates the Target state. + + Attributes: + details (Sequence[~.common.TargetDetails]): + Details about Agones fleets. + """ + + details = proto.RepeatedField(proto.MESSAGE, number=1, message=TargetDetails,) + + +class DeployedFleetDetails(proto.Message): + r"""Details of the deployed Agones fleet. + + Attributes: + deployed_fleet (~.common.DeployedFleetDetails.DeployedFleet): + Information about the Agones fleet. + deployed_autoscaler (~.common.DeployedFleetDetails.DeployedFleetAutoscaler): + Information about the Agones autoscaler for + that fleet. + """ + + class DeployedFleet(proto.Message): + r"""Agones fleet specification and details. + + Attributes: + fleet (str): + The name of the Agones fleet. + fleet_spec (str): + The fleet spec retrieved from the Agones + fleet. + spec_source (~.common.SpecSource): + The source spec that is used to create the + Agones fleet. The GameServerConfig resource may + no longer exist in the system. + status (~.common.DeployedFleetDetails.DeployedFleet.DeployedFleetStatus): + The current status of the Agones fleet. + Includes count of game servers in various + states. + """ + + class DeployedFleetStatus(proto.Message): + r"""DeployedFleetStatus has details about the Agones fleets such + as how many are running, how many allocated, and so on. + + Attributes: + ready_replicas (int): + The number of GameServer replicas in the + READY state in this fleet. + allocated_replicas (int): + The number of GameServer replicas in the + ALLOCATED state in this fleet. + reserved_replicas (int): + The number of GameServer replicas in the + RESERVED state in this fleet. Reserved instances + won't be deleted on scale down, but won't cause + an autoscaler to scale up. + replicas (int): + The total number of current GameServer + replicas in this fleet. + """ + + 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,) + + status = proto.Field( + proto.MESSAGE, + number=5, + message="DeployedFleetDetails.DeployedFleet.DeployedFleetStatus", + ) + + class DeployedFleetAutoscaler(proto.Message): + r"""Details about the Agones autoscaler. + + Attributes: + autoscaler (str): + The name of the Agones autoscaler. + spec_source (~.common.SpecSource): + The source spec that is used to create the + autoscaler. The GameServerConfig resource may no + longer exist in the system. + fleet_autoscaler_spec (str): + The autoscaler spec retrieved from Agones. + """ + + autoscaler = proto.Field(proto.STRING, number=1) + + 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_autoscaler = proto.Field( + proto.MESSAGE, number=2, message=DeployedFleetAutoscaler, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/game_server_clusters.py b/google/cloud/gaming_v1beta/types/game_server_clusters.py new file mode 100644 index 00000000..f6b7f16d --- /dev/null +++ b/google/cloud/gaming_v1beta/types/game_server_clusters.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.gaming_v1beta.types import common +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.gaming.v1beta", + manifest={ + "ListGameServerClustersRequest", + "ListGameServerClustersResponse", + "GetGameServerClusterRequest", + "CreateGameServerClusterRequest", + "PreviewCreateGameServerClusterRequest", + "PreviewCreateGameServerClusterResponse", + "DeleteGameServerClusterRequest", + "PreviewDeleteGameServerClusterRequest", + "PreviewDeleteGameServerClusterResponse", + "UpdateGameServerClusterRequest", + "PreviewUpdateGameServerClusterRequest", + "PreviewUpdateGameServerClusterResponse", + "GameServerClusterConnectionInfo", + "GkeClusterReference", + "GameServerCluster", + }, +) + + +class ListGameServerClustersRequest(proto.Message): + r"""Request message for + GameServerClustersService.ListGameServerClusters. + + Attributes: + parent (str): + Required. The parent resource name. Uses the + form: + "projects/{project}/locations/{location}/realms/{realm}". + page_size (int): + Optional. The maximum number of items to return. If + 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. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specifies the ordering of results following syntax + at + https://cloud.google.com/apis/design/design_patterns#sorting_order. + """ + + 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) + + +class ListGameServerClustersResponse(proto.Message): + r"""Response message for + GameServerClustersService.ListGameServerClusters. + + Attributes: + game_server_clusters (Sequence[~.gcg_game_server_clusters.GameServerCluster]): + 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. + """ + + @property + def raw_page(self): + return self + + game_server_clusters = proto.RepeatedField( + proto.MESSAGE, number=1, message="GameServerCluster", + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + unreachable = proto.RepeatedField(proto.STRING, number=4) + + +class GetGameServerClusterRequest(proto.Message): + r"""Request message for + GameServerClustersService.GetGameServerCluster. + + Attributes: + name (str): + Required. The name of the game server cluster to retrieve. + Uses the form: + + ``projects/{project}/locations/{location}/realms/{realm-id}/gameServerClusters/{cluster}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateGameServerClusterRequest(proto.Message): + r"""Request message for + GameServerClustersService.CreateGameServerCluster. + + Attributes: + parent (str): + 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 + resource to be created. + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): + 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", + ) + + +class PreviewCreateGameServerClusterRequest(proto.Message): + r"""Request message for + GameServerClustersService.PreviewCreateGameServerCluster. + + Attributes: + parent (str): + 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 + resource to be created. + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): + Required. The game server cluster resource to + be created. + preview_time (~.timestamp.Timestamp): + Optional. The target timestamp to compute the + preview. + """ + + 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", + ) + + preview_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + +class PreviewCreateGameServerClusterResponse(proto.Message): + r"""Response message for + GameServerClustersService.PreviewCreateGameServerCluster. + + Attributes: + etag (str): + The ETag of the game server cluster. + target_state (~.common.TargetState): + The target state. + """ + + etag = proto.Field(proto.STRING, number=2) + + target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,) + + +class DeleteGameServerClusterRequest(proto.Message): + r"""Request message for + GameServerClustersService.DeleteGameServerCluster. + + Attributes: + name (str): + Required. The name of the game server cluster to delete. + Uses the form: + ``projects/{project}/locations/{location}/gameServerClusters/{cluster}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class PreviewDeleteGameServerClusterRequest(proto.Message): + r"""Request message for + GameServerClustersService.PreviewDeleteGameServerCluster. + + Attributes: + name (str): + Required. The name of the game server cluster to delete. + Uses the form: + ``projects/{project}/locations/{location}/gameServerClusters/{cluster}``. + preview_time (~.timestamp.Timestamp): + Optional. The target timestamp to compute the + preview. + """ + + name = proto.Field(proto.STRING, number=1) + + preview_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + +class PreviewDeleteGameServerClusterResponse(proto.Message): + r"""Response message for + GameServerClustersService.PreviewDeleteGameServerCluster. + + Attributes: + etag (str): + The ETag of the game server cluster. + target_state (~.common.TargetState): + The target state. + """ + + etag = proto.Field(proto.STRING, number=2) + + target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,) + + +class UpdateGameServerClusterRequest(proto.Message): + r"""Request message for + GameServerClustersService.UpdateGameServerCluster. + + Attributes: + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): + 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 + be supplied in this field. For the ``FieldMask`` definition, + see + + https: //developers.google.com/protocol-buffers // + /docs/reference/google.protobuf#fieldmask + """ + + game_server_cluster = proto.Field( + proto.MESSAGE, number=1, message="GameServerCluster", + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class PreviewUpdateGameServerClusterRequest(proto.Message): + r"""Request message for + GameServerClustersService.UpdateGameServerCluster. + + Attributes: + game_server_cluster (~.gcg_game_server_clusters.GameServerCluster): + 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 + be supplied in this field. For the ``FieldMask`` definition, + see + + https: //developers.google.com/protocol-buffers // + /docs/reference/google.protobuf#fieldmask + preview_time (~.timestamp.Timestamp): + Optional. The target timestamp to compute the + preview. + """ + + game_server_cluster = proto.Field( + 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,) + + +class PreviewUpdateGameServerClusterResponse(proto.Message): + r"""Response message for + GameServerClustersService.PreviewUpdateGameServerCluster + + Attributes: + etag (str): + The ETag of the game server cluster. + target_state (~.common.TargetState): + The target state. + """ + + etag = proto.Field(proto.STRING, number=2) + + target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,) + + +class GameServerClusterConnectionInfo(proto.Message): + r"""The game server cluster connection information. + + Attributes: + gke_cluster_reference (~.gcg_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 + will be created. Existence of the namespace will + be validated during creation. + """ + + gke_cluster_reference = proto.Field( + proto.MESSAGE, + number=7, + oneof="cluster_reference", + message="GkeClusterReference", + ) + + namespace = proto.Field(proto.STRING, number=5) + + +class GkeClusterReference(proto.Message): + r"""A reference to a GKE cluster. + + Attributes: + cluster (str): + The full or partial name of a GKE cluster, using one of the + following forms: + + - ``projects/{project}/locations/{location}/clusters/{cluster}`` + - ``locations/{location}/clusters/{cluster}`` + - ``{cluster}`` If project and location are not specified, + the project and location of the GameServerCluster + resource are used to generate the full name of the GKE + cluster. + """ + + cluster = proto.Field(proto.STRING, number=1) + + +class GameServerCluster(proto.Message): + r"""A game server cluster resource. + + Attributes: + name (str): + Required. The resource name of the game server cluster. Uses + the form: + + ``projects/{project}/locations/{location}/realms/{realm}/gameServerClusters/{cluster}``. + For example, + + ``projects/my-project/locations/{location}/realms/zanzibar/gameServerClusters/my-onprem-cluster``. + create_time (~.timestamp.Timestamp): + Output only. The creation time. + update_time (~.timestamp.Timestamp): + Output only. The last-modified time. + labels (Sequence[~.gcg_game_server_clusters.GameServerCluster.LabelsEntry]): + The labels associated with this game server + cluster. Each label is a key-value pair. + connection_info (~.gcg_game_server_clusters.GameServerClusterConnectionInfo): + The game server cluster connection + information. This information is used to manage + game server clusters. + etag (str): + ETag of the resource. + description (str): + Human readable description of the cluster. + """ + + 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,) + + labels = proto.MapField(proto.STRING, proto.STRING, number=4) + + connection_info = proto.Field( + proto.MESSAGE, number=5, message=GameServerClusterConnectionInfo, + ) + + etag = proto.Field(proto.STRING, number=6) + + description = proto.Field(proto.STRING, number=7) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/game_server_clusters_service.py b/google/cloud/gaming_v1beta/types/game_server_clusters_service.py new file mode 100644 index 00000000..87138f5c --- /dev/null +++ b/google/cloud/gaming_v1beta/types/game_server_clusters_service.py @@ -0,0 +1,22 @@ +# -*- 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. +# + + +__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/game_server_configs.py b/google/cloud/gaming_v1beta/types/game_server_configs.py new file mode 100644 index 00000000..c662b16d --- /dev/null +++ b/google/cloud/gaming_v1beta/types/game_server_configs.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.gaming_v1beta.types import common +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.gaming.v1beta", + manifest={ + "ListGameServerConfigsRequest", + "ListGameServerConfigsResponse", + "GetGameServerConfigRequest", + "CreateGameServerConfigRequest", + "DeleteGameServerConfigRequest", + "ScalingConfig", + "FleetConfig", + "GameServerConfig", + }, +) + + +class ListGameServerConfigsRequest(proto.Message): + r"""Request message for + GameServerConfigsService.ListGameServerConfigs. + + Attributes: + parent (str): + Required. The parent resource name. Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/*``. + 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 + [next_page_token][google.cloud.gaming.v1beta.ListGameServerConfigsResponse.next_page_token] + to determine if there are more GameServerConfigs left to be + queried. + page_token (str): + Optional. The next_page_token value returned from a previous + list request, if any. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specifies the ordering of results following syntax + at + https://cloud.google.com/apis/design/design_patterns#sorting_order. + """ + + 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) + + +class ListGameServerConfigsResponse(proto.Message): + r"""Response message for + GameServerConfigsService.ListGameServerConfigs. + + Attributes: + game_server_configs (Sequence[~.gcg_game_server_configs.GameServerConfig]): + 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. + """ + + @property + def raw_page(self): + return self + + game_server_configs = proto.RepeatedField( + proto.MESSAGE, number=1, message="GameServerConfig", + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + unreachable = proto.RepeatedField(proto.STRING, number=4) + + +class GetGameServerConfigRequest(proto.Message): + r"""Request message for + GameServerConfigsService.GetGameServerConfig. + + Attributes: + name (str): + Required. The name of the game server config to retrieve. + Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateGameServerConfigRequest(proto.Message): + r"""Request message for + GameServerConfigsService.CreateGameServerConfig. + + Attributes: + parent (str): + Required. The parent resource name. Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/``. + config_id (str): + Required. The ID of the game server config + resource to be created. + game_server_config (~.gcg_game_server_configs.GameServerConfig): + 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", + ) + + +class DeleteGameServerConfigRequest(proto.Message): + r"""Request message for + GameServerConfigsService.DeleteGameServerConfig. + + Attributes: + name (str): + Required. The name of the game server config to delete. Uses + the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class ScalingConfig(proto.Message): + r"""Autoscaling config for an Agones fleet. + + Attributes: + name (str): + Required. The name of the Scaling Config + fleet_autoscaler_spec (str): + Required. Agones fleet autoscaler spec. + 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 + this Agones scaling config if its labels match + any of the selector entries. + schedules (Sequence[~.common.Schedule]): + The schedules to which this Scaling Config + applies. + """ + + 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, + ) + + schedules = proto.RepeatedField(proto.MESSAGE, number=5, message=common.Schedule,) + + +class FleetConfig(proto.Message): + r"""Fleet configs for Agones. + + Attributes: + fleet_spec (str): + Agones fleet spec. Example spec: + ``https://agones.dev/site/docs/reference/fleet/``. + name (str): + The name of the FleetConfig. + """ + + 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. + + Attributes: + name (str): + The resource name of the game server config. Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/configs/{config}``. + For example, + + ``projects/my-project/locations/global/gameServerDeployments/my-game/configs/my-config``. + create_time (~.timestamp.Timestamp): + Output only. The creation time. + update_time (~.timestamp.Timestamp): + Output only. The last-modified time. + labels (Sequence[~.gcg_game_server_configs.GameServerConfig.LabelsEntry]): + The labels associated with this game server + config. Each label is a key-value pair. + fleet_configs (Sequence[~.gcg_game_server_configs.FleetConfig]): + FleetConfig contains a list of Agones fleet + specs. Only one FleetConfig is allowed. + scaling_configs (Sequence[~.gcg_game_server_configs.ScalingConfig]): + The autoscaling settings. + description (str): + 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,) + + labels = proto.MapField(proto.STRING, proto.STRING, number=4) + + fleet_configs = proto.RepeatedField(proto.MESSAGE, number=5, message=FleetConfig,) + + scaling_configs = proto.RepeatedField( + proto.MESSAGE, number=6, message=ScalingConfig, + ) + + description = proto.Field(proto.STRING, number=7) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/game_server_configs_service.py b/google/cloud/gaming_v1beta/types/game_server_configs_service.py new file mode 100644 index 00000000..87138f5c --- /dev/null +++ b/google/cloud/gaming_v1beta/types/game_server_configs_service.py @@ -0,0 +1,22 @@ +# -*- 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. +# + + +__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/game_server_deployments.py b/google/cloud/gaming_v1beta/types/game_server_deployments.py new file mode 100644 index 00000000..761e3a2a --- /dev/null +++ b/google/cloud/gaming_v1beta/types/game_server_deployments.py @@ -0,0 +1,437 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.gaming_v1beta.types import common +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.gaming.v1beta", + manifest={ + "ListGameServerDeploymentsRequest", + "ListGameServerDeploymentsResponse", + "GetGameServerDeploymentRequest", + "GetGameServerDeploymentRolloutRequest", + "CreateGameServerDeploymentRequest", + "DeleteGameServerDeploymentRequest", + "UpdateGameServerDeploymentRequest", + "UpdateGameServerDeploymentRolloutRequest", + "FetchDeploymentStateRequest", + "FetchDeploymentStateResponse", + "GameServerDeployment", + "GameServerConfigOverride", + "GameServerDeploymentRollout", + "PreviewGameServerDeploymentRolloutRequest", + "PreviewGameServerDeploymentRolloutResponse", + }, +) + + +class ListGameServerDeploymentsRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.ListGameServerDeployments. + + Attributes: + parent (str): + Required. The parent resource name. Uses the form: + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. The maximum number of items to return. If + 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. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specifies the ordering of results following syntax + at + https://cloud.google.com/apis/design/design_patterns#sorting_order. + """ + + 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) + + +class ListGameServerDeploymentsResponse(proto.Message): + r"""Response message for + GameServerDeploymentsService.ListGameServerDeployments. + + Attributes: + game_server_deployments (Sequence[~.gcg_game_server_deployments.GameServerDeployment]): + 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. + """ + + @property + def raw_page(self): + return self + + game_server_deployments = proto.RepeatedField( + proto.MESSAGE, number=1, message="GameServerDeployment", + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + unreachable = proto.RepeatedField(proto.STRING, number=4) + + +class GetGameServerDeploymentRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.GetGameServerDeployment. + + Attributes: + name (str): + Required. The name of the game server delpoyment to + retrieve. Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetGameServerDeploymentRolloutRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.GetGameServerDeploymentRollout. + + Attributes: + name (str): + Required. The name of the game server delpoyment to + retrieve. Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateGameServerDeploymentRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.CreateGameServerDeployment. + + Attributes: + parent (str): + Required. The parent resource name. Uses the form: + ``projects/{project}/locations/{location}``. + deployment_id (str): + Required. The ID of the game server + delpoyment resource to be created. + game_server_deployment (~.gcg_game_server_deployments.GameServerDeployment): + 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", + ) + + +class DeleteGameServerDeploymentRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.DeleteGameServerDeployment. + + Attributes: + name (str): + Required. The name of the game server delpoyment to delete. + Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateGameServerDeploymentRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.UpdateGameServerDeployment. Only + allows updates for labels. + + Attributes: + game_server_deployment (~.gcg_game_server_deployments.GameServerDeployment): + 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 + be supplied in this field. For the ``FieldMask`` definition, + see + + https: //developers.google.com/protocol-buffers // + /docs/reference/google.protobuf#fieldmask + """ + + game_server_deployment = proto.Field( + proto.MESSAGE, number=1, message="GameServerDeployment", + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class UpdateGameServerDeploymentRolloutRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.UpdateGameServerRolloutDeployment. + + Attributes: + rollout (~.gcg_game_server_deployments.GameServerDeploymentRollout): + 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 + be supplied in this field. For the ``FieldMask`` definition, + see + + https: //developers.google.com/protocol-buffers // + /docs/reference/google.protobuf#fieldmask + """ + + rollout = proto.Field( + proto.MESSAGE, number=1, message="GameServerDeploymentRollout", + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class FetchDeploymentStateRequest(proto.Message): + r"""Request message for + GameServerDeploymentsService.FetchDeploymentState. + + Attributes: + name (str): + Required. The name of the game server delpoyment. Uses the + form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class FetchDeploymentStateResponse(proto.Message): + r"""Response message for + GameServerDeploymentsService.FetchDeploymentState. + + Attributes: + cluster_state (Sequence[~.gcg_game_server_deployments.FetchDeploymentStateResponse.DeployedClusterState]): + The state of the game server deployment in + each game server cluster. + unavailable (Sequence[str]): + List of locations that could not be reached. + """ + + class DeployedClusterState(proto.Message): + 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. + """ + + cluster = proto.Field(proto.STRING, number=1) + + fleet_details = proto.RepeatedField( + proto.MESSAGE, number=2, message=common.DeployedFleetDetails, + ) + + cluster_state = proto.RepeatedField( + proto.MESSAGE, number=1, message=DeployedClusterState, + ) + + unavailable = proto.RepeatedField(proto.STRING, number=2) + + +class GameServerDeployment(proto.Message): + r"""A game server deployment resource. + + Attributes: + name (str): + The resource name of the game server deployment. Uses the + form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}``. + For example, + + ``projects/my-project/locations/{location}/gameServerDeployments/my-deployment``. + create_time (~.timestamp.Timestamp): + Output only. The creation time. + update_time (~.timestamp.Timestamp): + Output only. The last-modified time. + labels (Sequence[~.gcg_game_server_deployments.GameServerDeployment.LabelsEntry]): + 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 + 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,) + + 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. + + Attributes: + realms_selector (~.common.RealmSelector): + Selector for choosing applicable realms. + config_version (str): + The game server config for this override. + """ + + 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 + desired rollout state. + + Attributes: + name (str): + The resource name of the game server deployment rollout. + Uses the form: + + ``projects/{project}/locations/{location}/gameServerDeployments/{deployment}/rollout``. + For example, + + ``projects/my-project/locations/{location}/gameServerDeployments/my-deployment/rollout``. + create_time (~.timestamp.Timestamp): + Output only. The creation time. + 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, + + ``projects/my-project/locations/global/gameServerDeployments/my-game/configs/my-config``. + game_server_config_overrides (Sequence[~.gcg_game_server_deployments.GameServerConfigOverride]): + 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. + 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,) + + default_game_server_config = proto.Field(proto.STRING, number=4) + + game_server_config_overrides = proto.RepeatedField( + proto.MESSAGE, number=5, message=GameServerConfigOverride, + ) + + etag = proto.Field(proto.STRING, number=6) + + +class PreviewGameServerDeploymentRolloutRequest(proto.Message): + r"""Request message for PreviewGameServerDeploymentRollout. + + Attributes: + rollout (~.gcg_game_server_deployments.GameServerDeploymentRollout): + 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 + be supplied in this field. For the ``FieldMask`` definition, + see + + https: //developers.google.com/protocol-buffers // + /docs/reference/google.protobuf#fieldmask + preview_time (~.timestamp.Timestamp): + Optional. The target timestamp to compute the + preview. Defaults to the immediately after the + 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,) + + +class PreviewGameServerDeploymentRolloutResponse(proto.Message): + r"""Response message for PreviewGameServerDeploymentRollout. + This has details about the Agones fleet and autoscaler to be + actuated. + + Attributes: + unavailable (Sequence[str]): + Locations that could not be reached on this + request. + etag (str): + 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,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/game_server_deployments_service.py b/google/cloud/gaming_v1beta/types/game_server_deployments_service.py new file mode 100644 index 00000000..87138f5c --- /dev/null +++ b/google/cloud/gaming_v1beta/types/game_server_deployments_service.py @@ -0,0 +1,22 @@ +# -*- 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. +# + + +__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/realms.py b/google/cloud/gaming_v1beta/types/realms.py new file mode 100644 index 00000000..56884286 --- /dev/null +++ b/google/cloud/gaming_v1beta/types/realms.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.gaming_v1beta.types import common +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.gaming.v1beta", + manifest={ + "ListRealmsRequest", + "ListRealmsResponse", + "GetRealmRequest", + "CreateRealmRequest", + "DeleteRealmRequest", + "UpdateRealmRequest", + "PreviewRealmUpdateRequest", + "PreviewRealmUpdateResponse", + "Realm", + }, +) + + +class ListRealmsRequest(proto.Message): + r"""Request message for RealmsService.ListRealms. + + Attributes: + parent (str): + Required. The parent resource name. Uses the form: + ``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 + [next_page_token][google.cloud.gaming.v1beta.ListRealmsResponse.next_page_token] + 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. + filter (str): + Optional. The filter to apply to list + results. + order_by (str): + Optional. Specifies the ordering of results following syntax + at + https://cloud.google.com/apis/design/design_patterns#sorting_order. + """ + + 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) + + +class ListRealmsResponse(proto.Message): + r"""Response message for RealmsService.ListRealms. + + Attributes: + realms (Sequence[~.gcg_realms.Realm]): + 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. + """ + + @property + def raw_page(self): + return self + + 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) + + +class GetRealmRequest(proto.Message): + r"""Request message for RealmsService.GetRealm. + + Attributes: + name (str): + Required. The name of the realm to retrieve. Uses the form: + ``projects/{project}/locations/{location}/realms/{realm}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateRealmRequest(proto.Message): + r"""Request message for RealmsService.CreateRealm. + + Attributes: + parent (str): + Required. The parent resource name. Uses the form: + ``projects/{project}/locations/{location}``. + realm_id (str): + Required. The ID of the realm resource to be + created. + realm (~.gcg_realms.Realm): + 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",) + + +class DeleteRealmRequest(proto.Message): + r"""Request message for RealmsService.DeleteRealm. + + Attributes: + name (str): + Required. The name of the realm to delete. Uses the form: + ``projects/{project}/locations/{location}/realms/{realm}``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateRealmRequest(proto.Message): + r"""Request message for RealmsService.UpdateRealm. + + Attributes: + realm (~.gcg_realms.Realm): + 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 + ``FieldMask`` definition, see + + https: //developers.google.com/protocol-buffers // + /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,) + + +class PreviewRealmUpdateRequest(proto.Message): + r"""Request message for RealmsService.PreviewRealmUpdate. + + Attributes: + realm (~.gcg_realms.Realm): + 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 + ``FieldMask`` definition, see + + https: //developers.google.com/protocol-buffers // + /docs/reference/google.protobuf#fieldmask + preview_time (~.timestamp.Timestamp): + Optional. The target timestamp to compute the + 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,) + + +class PreviewRealmUpdateResponse(proto.Message): + r"""Response message for RealmsService.PreviewRealmUpdate. + + Attributes: + etag (str): + ETag of the realm. + target_state (~.common.TargetState): + The target state. + """ + + etag = proto.Field(proto.STRING, number=2) + + target_state = proto.Field(proto.MESSAGE, number=3, message=common.TargetState,) + + +class Realm(proto.Message): + r"""A realm resource. + + Attributes: + name (str): + 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``. + create_time (~.timestamp.Timestamp): + Output only. The creation time. + update_time (~.timestamp.Timestamp): + Output only. The last-modified time. + labels (Sequence[~.gcg_realms.Realm.LabelsEntry]): + 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 + 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. + """ + + 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,) + + 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) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/gaming_v1beta/types/realms_service.py b/google/cloud/gaming_v1beta/types/realms_service.py new file mode 100644 index 00000000..87138f5c --- /dev/null +++ b/google/cloud/gaming_v1beta/types/realms_service.py @@ -0,0 +1,22 @@ +# -*- 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. +# + + +__protobuf__ = proto.module(package="google.cloud.gaming.v1beta", manifest={},) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/noxfile.py b/noxfile.py index fb0a9db2..ea5ed9f8 100644 --- a/noxfile.py +++ b/noxfile.py @@ -102,6 +102,10 @@ def system(session): """Run the system test suite.""" system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") @@ -162,3 +166,36 @@ def docs(session): os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install("sphinx", "alabaster", "recommonmark", "sphinx-docfx-yaml") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/scripts/fixup_gaming_v1_keywords.py b/scripts/fixup_gaming_v1_keywords.py index 3a315945..e7239f29 100644 --- a/scripts/fixup_gaming_v1_keywords.py +++ b/scripts/fixup_gaming_v1_keywords.py @@ -67,6 +67,7 @@ class gamingCallTransformer(cst.CSTTransformer): '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: diff --git a/scripts/fixup_gaming_v1beta_keywords.py b/scripts/fixup_gaming_v1beta_keywords.py new file mode 100644 index 00000000..e7239f29 --- /dev/null +++ b/scripts/fixup_gaming_v1beta_keywords.py @@ -0,0 +1,204 @@ +# -*- 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/setup.py b/setup.py index dd7075a6..b9de4e02 100644 --- a/setup.py +++ b/setup.py @@ -40,9 +40,9 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core[grpc] >= 1.21.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "googleapis-common-protos >= 1.5.8", - "proto-plus >= 0.4.0", + "proto-plus >= 1.4.0", ), python_requires=">=3.6", setup_requires=["libcst >= 0.2.5"], diff --git a/synth.metadata b/synth.metadata index a8024a0c..1ff1175c 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-game-servers.git", - "sha": "1c69b1ed137047c80e65a0545a56c191baa1f4ab" + "remote": "git@github.com:googleapis/python-game-servers", + "sha": "ee9347879e35c0b95a90391ca61692b54fb8e0cf" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "67415b43e7435d98ec104bca8cdaf4abfd3e8338", - "internalRef": "320987315" + "sha": "80442a7b7dbc10e27138e65bfc2cb28935d28f61", + "internalRef": "324717428" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "3a89215abd0e66dfc4f21d07d552d0b543abf082" + "sha": "4f8f5dc24af79694887385015294e4dbb214c352" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "3a89215abd0e66dfc4f21d07d552d0b543abf082" + "sha": "4f8f5dc24af79694887385015294e4dbb214c352" } } ], @@ -37,7 +37,16 @@ "apiName": "gameservices", "apiVersion": "v1beta", "language": "python", - "generator": "gapic-generator-python" + "generator": "bazel" + } + }, + { + "client": { + "source": "googleapis", + "apiName": "gameservices", + "apiVersion": "v1", + "language": "python", + "generator": "bazel" } } ] diff --git a/synth.py b/synth.py index 7d375f37..4bbc0be3 100644 --- a/synth.py +++ b/synth.py @@ -19,21 +19,21 @@ import synthtool.gcp as gcp from synthtool.languages import python -gapic = gcp.GAPICMicrogenerator() +gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() # ---------------------------------------------------------------------------- # Generate Game Servers GAPIC layer # ---------------------------------------------------------------------------- -library = gapic.py_library( - "gameservices", "v1beta", proto_path="google/cloud/gaming/v1beta" -) -s.move(library, excludes=["nox.py", "setup.py", "README.rst", "docs/index.rst"]) +versions = ["v1beta", "v1"] +for version in versions: + library = gapic.py_library( + "gameservices", version, bazel_target=f"//google/cloud/gaming/{version}:gaming-{version}-py" + ) + + s.move(library, excludes=["nox.py", "setup.py", "README.rst", "docs/index.rst"]) -# correct license headers -python.fix_pb2_headers() -python.fix_pb2_grpc_headers() # rename library to google-cloud-game-servers s.replace( diff --git a/tests/unit/gapic/gaming_v1/__init__.py b/tests/unit/gapic/gaming_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/gaming_v1/__init__.py @@ -0,0 +1 @@ + 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 index d6fa8fb8..3dfea2c7 100644 --- a/tests/unit/gapic/gaming_v1/test_game_server_clusters_service.py +++ b/tests/unit/gapic/gaming_v1/test_game_server_clusters_service.py @@ -55,6 +55,17 @@ def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" @@ -129,6 +140,16 @@ def test_game_server_clusters_service_client_get_transport_class(): ), ], ) +@mock.patch.object( + GameServerClustersServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerClustersServiceClient), +) +@mock.patch.object( + GameServerClustersServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerClustersServiceAsyncClient), +) def test_game_server_clusters_service_client_client_options( client_class, transport_class, transport_name ): @@ -159,64 +180,29 @@ def test_game_server_clusters_service_client_client_options( scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=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, - ) + with mock.patch.dict(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, + quota_project_id=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, - ): + with mock.patch.dict(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( @@ -226,34 +212,88 @@ def test_game_server_clusters_service_client_client_options( scopes=None, api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, client_cert_source=None, + quota_project_id=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, - ): + # "auto", and client_cert_source is provided. + with mock.patch.dict(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 = client_class(client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_ENDPOINT, + host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, ) + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=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() + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() - del os.environ["GOOGLE_API_USE_MTLS"] + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) @pytest.mark.parametrize( @@ -286,6 +326,7 @@ def test_game_server_clusters_service_client_client_options_scopes( scopes=["1", "2"], api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -319,6 +360,7 @@ def test_game_server_clusters_service_client_client_options_credentials_file( scopes=None, api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -337,17 +379,21 @@ def test_game_server_clusters_service_client_client_options_from_dict(): scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=None, ) -def test_list_game_server_clusters(transport: str = "grpc"): +def test_list_game_server_clusters( + transport: str = "grpc", + request_type=game_server_clusters.ListGameServerClustersRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -364,7 +410,7 @@ def test_list_game_server_clusters(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.ListGameServerClustersRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGameServerClustersPager) @@ -374,6 +420,10 @@ def test_list_game_server_clusters(transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] +def test_list_game_server_clusters_from_dict(): + test_list_game_server_clusters(request_type=dict) + + @pytest.mark.asyncio async def test_list_game_server_clusters_async(transport: str = "grpc_asyncio"): client = GameServerClustersServiceAsyncClient( @@ -732,14 +782,17 @@ async def test_list_game_server_clusters_async_pages(): assert page.raw_page.next_page_token == token -def test_get_game_server_cluster(transport: str = "grpc"): +def test_get_game_server_cluster( + transport: str = "grpc", + request_type=game_server_clusters.GetGameServerClusterRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -756,7 +809,7 @@ def test_get_game_server_cluster(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.GetGameServerClusterRequest() # Establish that the response is the type that we expect. assert isinstance(response, game_server_clusters.GameServerCluster) @@ -768,6 +821,10 @@ def test_get_game_server_cluster(transport: str = "grpc"): assert response.description == "description_value" +def test_get_game_server_cluster_from_dict(): + test_get_game_server_cluster(request_type=dict) + + @pytest.mark.asyncio async def test_get_game_server_cluster_async(transport: str = "grpc_asyncio"): client = GameServerClustersServiceAsyncClient( @@ -945,14 +1002,17 @@ async def test_get_game_server_cluster_flattened_error_async(): ) -def test_create_game_server_cluster(transport: str = "grpc"): +def test_create_game_server_cluster( + transport: str = "grpc", + request_type=game_server_clusters.CreateGameServerClusterRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -967,12 +1027,16 @@ def test_create_game_server_cluster(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.CreateGameServerClusterRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_create_game_server_cluster_from_dict(): + test_create_game_server_cluster(request_type=dict) + + @pytest.mark.asyncio async def test_create_game_server_cluster_async(transport: str = "grpc_asyncio"): client = GameServerClustersServiceAsyncClient( @@ -1176,14 +1240,17 @@ async def test_create_game_server_cluster_flattened_error_async(): ) -def test_preview_create_game_server_cluster(transport: str = "grpc"): +def test_preview_create_game_server_cluster( + transport: str = "grpc", + request_type=game_server_clusters.PreviewCreateGameServerClusterRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1200,7 +1267,7 @@ def test_preview_create_game_server_cluster(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.PreviewCreateGameServerClusterRequest() # Establish that the response is the type that we expect. assert isinstance( @@ -1210,6 +1277,10 @@ def test_preview_create_game_server_cluster(transport: str = "grpc"): assert response.etag == "etag_value" +def test_preview_create_game_server_cluster_from_dict(): + test_preview_create_game_server_cluster(request_type=dict) + + @pytest.mark.asyncio async def test_preview_create_game_server_cluster_async( transport: str = "grpc_asyncio", @@ -1310,14 +1381,17 @@ async def test_preview_create_game_server_cluster_field_headers_async(): assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] -def test_delete_game_server_cluster(transport: str = "grpc"): +def test_delete_game_server_cluster( + transport: str = "grpc", + request_type=game_server_clusters.DeleteGameServerClusterRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1332,12 +1406,16 @@ def test_delete_game_server_cluster(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.DeleteGameServerClusterRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_delete_game_server_cluster_from_dict(): + test_delete_game_server_cluster(request_type=dict) + + @pytest.mark.asyncio async def test_delete_game_server_cluster_async(transport: str = "grpc_asyncio"): client = GameServerClustersServiceAsyncClient( @@ -1507,14 +1585,17 @@ async def test_delete_game_server_cluster_flattened_error_async(): ) -def test_preview_delete_game_server_cluster(transport: str = "grpc"): +def test_preview_delete_game_server_cluster( + transport: str = "grpc", + request_type=game_server_clusters.PreviewDeleteGameServerClusterRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1531,7 +1612,7 @@ def test_preview_delete_game_server_cluster(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.PreviewDeleteGameServerClusterRequest() # Establish that the response is the type that we expect. assert isinstance( @@ -1541,6 +1622,10 @@ def test_preview_delete_game_server_cluster(transport: str = "grpc"): assert response.etag == "etag_value" +def test_preview_delete_game_server_cluster_from_dict(): + test_preview_delete_game_server_cluster(request_type=dict) + + @pytest.mark.asyncio async def test_preview_delete_game_server_cluster_async( transport: str = "grpc_asyncio", @@ -1641,14 +1726,17 @@ async def test_preview_delete_game_server_cluster_field_headers_async(): assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] -def test_update_game_server_cluster(transport: str = "grpc"): +def test_update_game_server_cluster( + transport: str = "grpc", + request_type=game_server_clusters.UpdateGameServerClusterRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1663,12 +1751,16 @@ def test_update_game_server_cluster(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.UpdateGameServerClusterRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_update_game_server_cluster_from_dict(): + test_update_game_server_cluster(request_type=dict) + + @pytest.mark.asyncio async def test_update_game_server_cluster_async(transport: str = "grpc_asyncio"): client = GameServerClustersServiceAsyncClient( @@ -1870,14 +1962,17 @@ async def test_update_game_server_cluster_flattened_error_async(): ) -def test_preview_update_game_server_cluster(transport: str = "grpc"): +def test_preview_update_game_server_cluster( + transport: str = "grpc", + request_type=game_server_clusters.PreviewUpdateGameServerClusterRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1894,7 +1989,7 @@ def test_preview_update_game_server_cluster(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_clusters.PreviewUpdateGameServerClusterRequest() # Establish that the response is the type that we expect. assert isinstance( @@ -1904,6 +1999,10 @@ def test_preview_update_game_server_cluster(transport: str = "grpc"): assert response.etag == "etag_value" +def test_preview_update_game_server_cluster_from_dict(): + test_preview_update_game_server_cluster(request_type=dict) + + @pytest.mark.asyncio async def test_preview_update_game_server_cluster_async( transport: str = "grpc_asyncio", @@ -2085,9 +2184,13 @@ def test_game_server_clusters_service_base_transport_error(): def test_game_server_clusters_service_base_transport(): # Instantiate the base transport. - transport = transports.GameServerClustersServiceTransport( - credentials=credentials.AnonymousCredentials(), - ) + with mock.patch( + "google.cloud.gaming_v1.services.game_server_clusters_service.transports.GameServerClustersServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GameServerClustersServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) # Every method on the transport should just blindly # raise NotImplementedError. @@ -2113,14 +2216,20 @@ def test_game_server_clusters_service_base_transport(): 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: + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.gaming_v1.services.game_server_clusters_service.transports.GameServerClustersServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None load_creds.return_value = (credentials.AnonymousCredentials(), None) transport = transports.GameServerClustersServiceTransport( - credentials_file="credentials.json", + credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -2130,7 +2239,8 @@ def test_game_server_clusters_service_auth_adc(): adc.return_value = (credentials.AnonymousCredentials(), None) GameServerClustersServiceClient() adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, ) @@ -2139,9 +2249,12 @@ def test_game_server_clusters_service_transport_auth_adc(): # ADC credentials. with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) - transports.GameServerClustersServiceGrpcTransport(host="squid.clam.whelk") + transports.GameServerClustersServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -2229,6 +2342,7 @@ def test_game_server_clusters_service_grpc_transport_channel_mtls_with_client_ce credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -2263,6 +2377,7 @@ def test_game_server_clusters_service_grpc_asyncio_transport_channel_mtls_with_c credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -2299,6 +2414,7 @@ def test_game_server_clusters_service_grpc_transport_channel_mtls_with_adc( credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -2335,6 +2451,7 @@ def test_game_server_clusters_service_grpc_asyncio_transport_channel_mtls_with_a credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel 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 index e46830c3..4e209ace 100644 --- a/tests/unit/gapic/gaming_v1/test_game_server_configs_service.py +++ b/tests/unit/gapic/gaming_v1/test_game_server_configs_service.py @@ -55,6 +55,17 @@ def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" @@ -127,6 +138,16 @@ def test_game_server_configs_service_client_get_transport_class(): ), ], ) +@mock.patch.object( + GameServerConfigsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerConfigsServiceClient), +) +@mock.patch.object( + GameServerConfigsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerConfigsServiceAsyncClient), +) def test_game_server_configs_service_client_client_options( client_class, transport_class, transport_name ): @@ -157,64 +178,29 @@ def test_game_server_configs_service_client_client_options( scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=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, - ) + with mock.patch.dict(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, + quota_project_id=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, - ): + with mock.patch.dict(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( @@ -224,34 +210,88 @@ def test_game_server_configs_service_client_client_options( scopes=None, api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, client_cert_source=None, + quota_project_id=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, - ): + # "auto", and client_cert_source is provided. + with mock.patch.dict(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 = client_class(client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_ENDPOINT, + host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, ) + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=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() + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() - del os.environ["GOOGLE_API_USE_MTLS"] + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) @pytest.mark.parametrize( @@ -284,6 +324,7 @@ def test_game_server_configs_service_client_client_options_scopes( scopes=["1", "2"], api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -317,6 +358,7 @@ def test_game_server_configs_service_client_client_options_credentials_file( scopes=None, api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -335,17 +377,21 @@ def test_game_server_configs_service_client_client_options_from_dict(): scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=None, ) -def test_list_game_server_configs(transport: str = "grpc"): +def test_list_game_server_configs( + transport: str = "grpc", + request_type=game_server_configs.ListGameServerConfigsRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -362,7 +408,7 @@ def test_list_game_server_configs(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_configs.ListGameServerConfigsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGameServerConfigsPager) @@ -372,6 +418,10 @@ def test_list_game_server_configs(transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] +def test_list_game_server_configs_from_dict(): + test_list_game_server_configs(request_type=dict) + + @pytest.mark.asyncio async def test_list_game_server_configs_async(transport: str = "grpc_asyncio"): client = GameServerConfigsServiceAsyncClient( @@ -728,14 +778,16 @@ async def test_list_game_server_configs_async_pages(): assert page.raw_page.next_page_token == token -def test_get_game_server_config(transport: str = "grpc"): +def test_get_game_server_config( + transport: str = "grpc", request_type=game_server_configs.GetGameServerConfigRequest +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -752,7 +804,7 @@ def test_get_game_server_config(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_configs.GetGameServerConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, game_server_configs.GameServerConfig) @@ -762,6 +814,10 @@ def test_get_game_server_config(transport: str = "grpc"): assert response.description == "description_value" +def test_get_game_server_config_from_dict(): + test_get_game_server_config(request_type=dict) + + @pytest.mark.asyncio async def test_get_game_server_config_async(transport: str = "grpc_asyncio"): client = GameServerConfigsServiceAsyncClient( @@ -937,14 +993,17 @@ async def test_get_game_server_config_flattened_error_async(): ) -def test_create_game_server_config(transport: str = "grpc"): +def test_create_game_server_config( + transport: str = "grpc", + request_type=game_server_configs.CreateGameServerConfigRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -959,12 +1018,16 @@ def test_create_game_server_config(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_configs.CreateGameServerConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_create_game_server_config_from_dict(): + test_create_game_server_config(request_type=dict) + + @pytest.mark.asyncio async def test_create_game_server_config_async(transport: str = "grpc_asyncio"): client = GameServerConfigsServiceAsyncClient( @@ -1152,14 +1215,17 @@ async def test_create_game_server_config_flattened_error_async(): ) -def test_delete_game_server_config(transport: str = "grpc"): +def test_delete_game_server_config( + transport: str = "grpc", + request_type=game_server_configs.DeleteGameServerConfigRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1174,12 +1240,16 @@ def test_delete_game_server_config(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_configs.DeleteGameServerConfigRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_delete_game_server_config_from_dict(): + test_delete_game_server_config(request_type=dict) + + @pytest.mark.asyncio async def test_delete_game_server_config_async(transport: str = "grpc_asyncio"): client = GameServerConfigsServiceAsyncClient( @@ -1424,9 +1494,13 @@ def test_game_server_configs_service_base_transport_error(): def test_game_server_configs_service_base_transport(): # Instantiate the base transport. - transport = transports.GameServerConfigsServiceTransport( - credentials=credentials.AnonymousCredentials(), - ) + with mock.patch( + "google.cloud.gaming_v1.services.game_server_configs_service.transports.GameServerConfigsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GameServerConfigsServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) # Every method on the transport should just blindly # raise NotImplementedError. @@ -1448,14 +1522,20 @@ def test_game_server_configs_service_base_transport(): 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: + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.gaming_v1.services.game_server_configs_service.transports.GameServerConfigsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None load_creds.return_value = (credentials.AnonymousCredentials(), None) transport = transports.GameServerConfigsServiceTransport( - credentials_file="credentials.json", + credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -1465,7 +1545,8 @@ def test_game_server_configs_service_auth_adc(): adc.return_value = (credentials.AnonymousCredentials(), None) GameServerConfigsServiceClient() adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, ) @@ -1474,9 +1555,12 @@ def test_game_server_configs_service_transport_auth_adc(): # ADC credentials. with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) - transports.GameServerConfigsServiceGrpcTransport(host="squid.clam.whelk") + transports.GameServerConfigsServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -1564,6 +1648,7 @@ def test_game_server_configs_service_grpc_transport_channel_mtls_with_client_cer credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -1598,6 +1683,7 @@ def test_game_server_configs_service_grpc_asyncio_transport_channel_mtls_with_cl credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -1634,6 +1720,7 @@ def test_game_server_configs_service_grpc_transport_channel_mtls_with_adc( credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -1670,6 +1757,7 @@ def test_game_server_configs_service_grpc_asyncio_transport_channel_mtls_with_ad credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel 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 index 65710221..de43fa13 100644 --- a/tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py +++ b/tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py @@ -55,6 +55,17 @@ def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" @@ -129,6 +140,16 @@ def test_game_server_deployments_service_client_get_transport_class(): ), ], ) +@mock.patch.object( + GameServerDeploymentsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerDeploymentsServiceClient), +) +@mock.patch.object( + GameServerDeploymentsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerDeploymentsServiceAsyncClient), +) def test_game_server_deployments_service_client_client_options( client_class, transport_class, transport_name ): @@ -159,64 +180,29 @@ def test_game_server_deployments_service_client_client_options( scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=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, - ) + with mock.patch.dict(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, + quota_project_id=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, - ): + with mock.patch.dict(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( @@ -226,34 +212,88 @@ def test_game_server_deployments_service_client_client_options( scopes=None, api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, client_cert_source=None, + quota_project_id=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, - ): + # "auto", and client_cert_source is provided. + with mock.patch.dict(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 = client_class(client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_ENDPOINT, + host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, ) + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=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() + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() - del os.environ["GOOGLE_API_USE_MTLS"] + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) @pytest.mark.parametrize( @@ -286,6 +326,7 @@ def test_game_server_deployments_service_client_client_options_scopes( scopes=["1", "2"], api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -319,6 +360,7 @@ def test_game_server_deployments_service_client_client_options_credentials_file( scopes=None, api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -337,17 +379,21 @@ def test_game_server_deployments_service_client_client_options_from_dict(): scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=None, ) -def test_list_game_server_deployments(transport: str = "grpc"): +def test_list_game_server_deployments( + transport: str = "grpc", + request_type=game_server_deployments.ListGameServerDeploymentsRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -364,7 +410,7 @@ def test_list_game_server_deployments(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_deployments.ListGameServerDeploymentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGameServerDeploymentsPager) @@ -374,6 +420,10 @@ def test_list_game_server_deployments(transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] +def test_list_game_server_deployments_from_dict(): + test_list_game_server_deployments(request_type=dict) + + @pytest.mark.asyncio async def test_list_game_server_deployments_async(transport: str = "grpc_asyncio"): client = GameServerDeploymentsServiceAsyncClient( @@ -743,14 +793,17 @@ async def test_list_game_server_deployments_async_pages(): assert page.raw_page.next_page_token == token -def test_get_game_server_deployment(transport: str = "grpc"): +def test_get_game_server_deployment( + transport: str = "grpc", + request_type=game_server_deployments.GetGameServerDeploymentRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -767,7 +820,7 @@ def test_get_game_server_deployment(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_deployments.GetGameServerDeploymentRequest() # Establish that the response is the type that we expect. assert isinstance(response, game_server_deployments.GameServerDeployment) @@ -779,6 +832,10 @@ def test_get_game_server_deployment(transport: str = "grpc"): assert response.description == "description_value" +def test_get_game_server_deployment_from_dict(): + test_get_game_server_deployment(request_type=dict) + + @pytest.mark.asyncio async def test_get_game_server_deployment_async(transport: str = "grpc_asyncio"): client = GameServerDeploymentsServiceAsyncClient( @@ -956,14 +1013,17 @@ async def test_get_game_server_deployment_flattened_error_async(): ) -def test_create_game_server_deployment(transport: str = "grpc"): +def test_create_game_server_deployment( + transport: str = "grpc", + request_type=game_server_deployments.CreateGameServerDeploymentRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -978,12 +1038,16 @@ def test_create_game_server_deployment(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_deployments.CreateGameServerDeploymentRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_create_game_server_deployment_from_dict(): + test_create_game_server_deployment(request_type=dict) + + @pytest.mark.asyncio async def test_create_game_server_deployment_async(transport: str = "grpc_asyncio"): client = GameServerDeploymentsServiceAsyncClient( @@ -1183,14 +1247,17 @@ async def test_create_game_server_deployment_flattened_error_async(): ) -def test_delete_game_server_deployment(transport: str = "grpc"): +def test_delete_game_server_deployment( + transport: str = "grpc", + request_type=game_server_deployments.DeleteGameServerDeploymentRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1205,12 +1272,16 @@ def test_delete_game_server_deployment(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_deployments.DeleteGameServerDeploymentRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_delete_game_server_deployment_from_dict(): + test_delete_game_server_deployment(request_type=dict) + + @pytest.mark.asyncio async def test_delete_game_server_deployment_async(transport: str = "grpc_asyncio"): client = GameServerDeploymentsServiceAsyncClient( @@ -1382,14 +1453,17 @@ async def test_delete_game_server_deployment_flattened_error_async(): ) -def test_update_game_server_deployment(transport: str = "grpc"): +def test_update_game_server_deployment( + transport: str = "grpc", + request_type=game_server_deployments.UpdateGameServerDeploymentRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1404,12 +1478,16 @@ def test_update_game_server_deployment(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_deployments.UpdateGameServerDeploymentRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_update_game_server_deployment_from_dict(): + test_update_game_server_deployment(request_type=dict) + + @pytest.mark.asyncio async def test_update_game_server_deployment_async(transport: str = "grpc_asyncio"): client = GameServerDeploymentsServiceAsyncClient( @@ -1615,14 +1693,17 @@ async def test_update_game_server_deployment_flattened_error_async(): ) -def test_get_game_server_deployment_rollout(transport: str = "grpc"): +def test_get_game_server_deployment_rollout( + transport: str = "grpc", + request_type=game_server_deployments.GetGameServerDeploymentRolloutRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1641,7 +1722,9 @@ def test_get_game_server_deployment_rollout(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert ( + args[0] == game_server_deployments.GetGameServerDeploymentRolloutRequest() + ) # Establish that the response is the type that we expect. assert isinstance(response, game_server_deployments.GameServerDeploymentRollout) @@ -1653,6 +1736,10 @@ def test_get_game_server_deployment_rollout(transport: str = "grpc"): assert response.etag == "etag_value" +def test_get_game_server_deployment_rollout_from_dict(): + test_get_game_server_deployment_rollout(request_type=dict) + + @pytest.mark.asyncio async def test_get_game_server_deployment_rollout_async( transport: str = "grpc_asyncio", @@ -1836,14 +1923,17 @@ async def test_get_game_server_deployment_rollout_flattened_error_async(): ) -def test_update_game_server_deployment_rollout(transport: str = "grpc"): +def test_update_game_server_deployment_rollout( + transport: str = "grpc", + request_type=game_server_deployments.UpdateGameServerDeploymentRolloutRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1858,12 +1948,19 @@ def test_update_game_server_deployment_rollout(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert ( + args[0] + == game_server_deployments.UpdateGameServerDeploymentRolloutRequest() + ) # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_update_game_server_deployment_rollout_from_dict(): + test_update_game_server_deployment_rollout(request_type=dict) + + @pytest.mark.asyncio async def test_update_game_server_deployment_rollout_async( transport: str = "grpc_asyncio", @@ -2068,14 +2165,17 @@ async def test_update_game_server_deployment_rollout_flattened_error_async(): ) -def test_preview_game_server_deployment_rollout(transport: str = "grpc"): +def test_preview_game_server_deployment_rollout( + transport: str = "grpc", + request_type=game_server_deployments.PreviewGameServerDeploymentRolloutRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2092,7 +2192,10 @@ def test_preview_game_server_deployment_rollout(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert ( + args[0] + == game_server_deployments.PreviewGameServerDeploymentRolloutRequest() + ) # Establish that the response is the type that we expect. assert isinstance( @@ -2104,6 +2207,10 @@ def test_preview_game_server_deployment_rollout(transport: str = "grpc"): assert response.etag == "etag_value" +def test_preview_game_server_deployment_rollout_from_dict(): + test_preview_game_server_deployment_rollout(request_type=dict) + + @pytest.mark.asyncio async def test_preview_game_server_deployment_rollout_async( transport: str = "grpc_asyncio", @@ -2212,14 +2319,17 @@ async def test_preview_game_server_deployment_rollout_field_headers_async(): ] -def test_fetch_deployment_state(transport: str = "grpc"): +def test_fetch_deployment_state( + transport: str = "grpc", + request_type=game_server_deployments.FetchDeploymentStateRequest, +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2236,7 +2346,7 @@ def test_fetch_deployment_state(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == game_server_deployments.FetchDeploymentStateRequest() # Establish that the response is the type that we expect. assert isinstance(response, game_server_deployments.FetchDeploymentStateResponse) @@ -2244,6 +2354,10 @@ def test_fetch_deployment_state(transport: str = "grpc"): assert response.unavailable == ["unavailable_value"] +def test_fetch_deployment_state_from_dict(): + test_fetch_deployment_state(request_type=dict) + + @pytest.mark.asyncio async def test_fetch_deployment_state_async(transport: str = "grpc_asyncio"): client = GameServerDeploymentsServiceAsyncClient( @@ -2413,9 +2527,13 @@ def test_game_server_deployments_service_base_transport_error(): def test_game_server_deployments_service_base_transport(): # Instantiate the base transport. - transport = transports.GameServerDeploymentsServiceTransport( - credentials=credentials.AnonymousCredentials(), - ) + with mock.patch( + "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GameServerDeploymentsServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) # Every method on the transport should just blindly # raise NotImplementedError. @@ -2442,14 +2560,20 @@ def test_game_server_deployments_service_base_transport(): 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: + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None load_creds.return_value = (credentials.AnonymousCredentials(), None) transport = transports.GameServerDeploymentsServiceTransport( - credentials_file="credentials.json", + credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -2459,7 +2583,8 @@ def test_game_server_deployments_service_auth_adc(): adc.return_value = (credentials.AnonymousCredentials(), None) GameServerDeploymentsServiceClient() adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, ) @@ -2468,9 +2593,12 @@ def test_game_server_deployments_service_transport_auth_adc(): # ADC credentials. with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) - transports.GameServerDeploymentsServiceGrpcTransport(host="squid.clam.whelk") + transports.GameServerDeploymentsServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -2558,6 +2686,7 @@ def test_game_server_deployments_service_grpc_transport_channel_mtls_with_client credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -2592,6 +2721,7 @@ def test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_wit credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -2628,6 +2758,7 @@ def test_game_server_deployments_service_grpc_transport_channel_mtls_with_adc( credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -2664,6 +2795,7 @@ def test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_wit credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/gaming_v1/test_realms_service.py b/tests/unit/gapic/gaming_v1/test_realms_service.py index 16ecfe32..1b2a75c7 100644 --- a/tests/unit/gapic/gaming_v1/test_realms_service.py +++ b/tests/unit/gapic/gaming_v1/test_realms_service.py @@ -51,6 +51,17 @@ def client_cert_source_callback(): return b"cert bytes", b"key bytes" +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" @@ -117,6 +128,16 @@ def test_realms_service_client_get_transport_class(): ), ], ) +@mock.patch.object( + RealmsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RealmsServiceClient), +) +@mock.patch.object( + RealmsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RealmsServiceAsyncClient), +) def test_realms_service_client_client_options( client_class, transport_class, transport_name ): @@ -143,64 +164,29 @@ def test_realms_service_client_client_options( scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=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, - ) + with mock.patch.dict(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, + quota_project_id=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, - ): + with mock.patch.dict(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( @@ -210,34 +196,88 @@ def test_realms_service_client_client_options( scopes=None, api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, client_cert_source=None, + quota_project_id=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, - ): + # "auto", and client_cert_source is provided. + with mock.patch.dict(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 = client_class(client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client.DEFAULT_ENDPOINT, + host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, ) + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=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() + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() - del os.environ["GOOGLE_API_USE_MTLS"] + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) @pytest.mark.parametrize( @@ -266,6 +306,7 @@ def test_realms_service_client_client_options_scopes( scopes=["1", "2"], api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -295,6 +336,7 @@ def test_realms_service_client_client_options_credentials_file( scopes=None, api_mtls_endpoint=client.DEFAULT_ENDPOINT, client_cert_source=None, + quota_project_id=None, ) @@ -313,17 +355,18 @@ def test_realms_service_client_client_options_from_dict(): scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, + quota_project_id=None, ) -def test_list_realms(transport: str = "grpc"): +def test_list_realms(transport: str = "grpc", request_type=realms.ListRealmsRequest): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client._transport.list_realms), "__call__") as call: @@ -338,7 +381,7 @@ def test_list_realms(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == realms.ListRealmsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRealmsPager) @@ -348,6 +391,10 @@ def test_list_realms(transport: str = "grpc"): assert response.unreachable == ["unreachable_value"] +def test_list_realms_from_dict(): + test_list_realms(request_type=dict) + + @pytest.mark.asyncio async def test_list_realms_async(transport: str = "grpc_asyncio"): client = RealmsServiceAsyncClient( @@ -618,14 +665,14 @@ async def test_list_realms_async_pages(): assert page.raw_page.next_page_token == token -def test_get_realm(transport: str = "grpc"): +def test_get_realm(transport: str = "grpc", request_type=realms.GetRealmRequest): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client._transport.get_realm), "__call__") as call: @@ -643,7 +690,7 @@ def test_get_realm(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == realms.GetRealmRequest() # Establish that the response is the type that we expect. assert isinstance(response, realms.Realm) @@ -657,6 +704,10 @@ def test_get_realm(transport: str = "grpc"): assert response.description == "description_value" +def test_get_realm_from_dict(): + test_get_realm(request_type=dict) + + @pytest.mark.asyncio async def test_get_realm_async(transport: str = "grpc_asyncio"): client = RealmsServiceAsyncClient( @@ -819,14 +870,14 @@ async def test_get_realm_flattened_error_async(): ) -def test_create_realm(transport: str = "grpc"): +def test_create_realm(transport: str = "grpc", request_type=realms.CreateRealmRequest): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client._transport.create_realm), "__call__") as call: @@ -839,12 +890,16 @@ def test_create_realm(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == realms.CreateRealmRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_create_realm_from_dict(): + test_create_realm(request_type=dict) + + @pytest.mark.asyncio async def test_create_realm_async(transport: str = "grpc_asyncio"): client = RealmsServiceAsyncClient( @@ -1020,14 +1075,14 @@ async def test_create_realm_flattened_error_async(): ) -def test_delete_realm(transport: str = "grpc"): +def test_delete_realm(transport: str = "grpc", request_type=realms.DeleteRealmRequest): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client._transport.delete_realm), "__call__") as call: @@ -1040,12 +1095,16 @@ def test_delete_realm(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == realms.DeleteRealmRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_delete_realm_from_dict(): + test_delete_realm(request_type=dict) + + @pytest.mark.asyncio async def test_delete_realm_async(transport: str = "grpc_asyncio"): client = RealmsServiceAsyncClient( @@ -1199,14 +1258,14 @@ async def test_delete_realm_flattened_error_async(): ) -def test_update_realm(transport: str = "grpc"): +def test_update_realm(transport: str = "grpc", request_type=realms.UpdateRealmRequest): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client._transport.update_realm), "__call__") as call: @@ -1219,12 +1278,16 @@ def test_update_realm(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == realms.UpdateRealmRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) +def test_update_realm_from_dict(): + test_update_realm(request_type=dict) + + @pytest.mark.asyncio async def test_update_realm_async(transport: str = "grpc_asyncio"): client = RealmsServiceAsyncClient( @@ -1392,14 +1455,16 @@ async def test_update_realm_flattened_error_async(): ) -def test_preview_realm_update(transport: str = "grpc"): +def test_preview_realm_update( + transport: str = "grpc", request_type=realms.PreviewRealmUpdateRequest +): 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() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1414,7 +1479,7 @@ def test_preview_realm_update(transport: str = "grpc"): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == realms.PreviewRealmUpdateRequest() # Establish that the response is the type that we expect. assert isinstance(response, realms.PreviewRealmUpdateResponse) @@ -1422,6 +1487,10 @@ def test_preview_realm_update(transport: str = "grpc"): assert response.etag == "etag_value" +def test_preview_realm_update_from_dict(): + test_preview_realm_update(request_type=dict) + + @pytest.mark.asyncio async def test_preview_realm_update_async(transport: str = "grpc_asyncio"): client = RealmsServiceAsyncClient( @@ -1581,9 +1650,13 @@ def test_realms_service_base_transport_error(): def test_realms_service_base_transport(): # Instantiate the base transport. - transport = transports.RealmsServiceTransport( - credentials=credentials.AnonymousCredentials(), - ) + with mock.patch( + "google.cloud.gaming_v1.services.realms_service.transports.RealmsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RealmsServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) # Every method on the transport should just blindly # raise NotImplementedError. @@ -1607,14 +1680,20 @@ def test_realms_service_base_transport(): 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: + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.gaming_v1.services.realms_service.transports.RealmsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None load_creds.return_value = (credentials.AnonymousCredentials(), None) transport = transports.RealmsServiceTransport( - credentials_file="credentials.json", + credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -1624,7 +1703,8 @@ def test_realms_service_auth_adc(): adc.return_value = (credentials.AnonymousCredentials(), None) RealmsServiceClient() adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, ) @@ -1633,9 +1713,12 @@ def test_realms_service_transport_auth_adc(): # ADC credentials. with mock.patch.object(auth, "default") as adc: adc.return_value = (credentials.AnonymousCredentials(), None) - transports.RealmsServiceGrpcTransport(host="squid.clam.whelk") + transports.RealmsServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) @@ -1723,6 +1806,7 @@ def test_realms_service_grpc_transport_channel_mtls_with_client_cert_source( credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -1757,6 +1841,7 @@ def test_realms_service_grpc_asyncio_transport_channel_mtls_with_client_cert_sou credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -1793,6 +1878,7 @@ def test_realms_service_grpc_transport_channel_mtls_with_adc( credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel @@ -1829,6 +1915,7 @@ def test_realms_service_grpc_asyncio_transport_channel_mtls_with_adc( credentials_file=None, scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, + quota_project_id=None, ) assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/gaming_v1beta/__init__.py b/tests/unit/gapic/gaming_v1beta/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/gaming_v1beta/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/gaming_v1beta/test_game_server_clusters_service.py b/tests/unit/gapic/gaming_v1beta/test_game_server_clusters_service.py new file mode 100644 index 00000000..1fa50a7c --- /dev/null +++ b/tests/unit/gapic/gaming_v1beta/test_game_server_clusters_service.py @@ -0,0 +1,2511 @@ +# -*- 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_v1beta.services.game_server_clusters_service import ( + GameServerClustersServiceAsyncClient, +) +from google.cloud.gaming_v1beta.services.game_server_clusters_service import ( + GameServerClustersServiceClient, +) +from google.cloud.gaming_v1beta.services.game_server_clusters_service import pagers +from google.cloud.gaming_v1beta.services.game_server_clusters_service import transports +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", + ), + ], +) +@mock.patch.object( + GameServerClustersServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerClustersServiceClient), +) +@mock.patch.object( + GameServerClustersServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerClustersServiceAsyncClient), +) +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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@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, + quota_project_id=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, + quota_project_id=None, + ) + + +def test_game_server_clusters_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.gaming_v1beta.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, + quota_project_id=None, + ) + + +def test_list_game_server_clusters( + transport: str = "grpc", + request_type=game_server_clusters.ListGameServerClustersRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.ListGameServerClustersRequest() + + # 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_from_dict(): + test_list_game_server_clusters(request_type=dict) + + +@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", + request_type=game_server_clusters.GetGameServerClusterRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.GetGameServerClusterRequest() + + # 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_from_dict(): + test_get_game_server_cluster(request_type=dict) + + +@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", + request_type=game_server_clusters.CreateGameServerClusterRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.CreateGameServerClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_game_server_cluster_from_dict(): + test_create_game_server_cluster(request_type=dict) + + +@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", + request_type=game_server_clusters.PreviewCreateGameServerClusterRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.PreviewCreateGameServerClusterRequest() + + # 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_from_dict(): + test_preview_create_game_server_cluster(request_type=dict) + + +@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", + request_type=game_server_clusters.DeleteGameServerClusterRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.DeleteGameServerClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_game_server_cluster_from_dict(): + test_delete_game_server_cluster(request_type=dict) + + +@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", + request_type=game_server_clusters.PreviewDeleteGameServerClusterRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.PreviewDeleteGameServerClusterRequest() + + # 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_from_dict(): + test_preview_delete_game_server_cluster(request_type=dict) + + +@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", + request_type=game_server_clusters.UpdateGameServerClusterRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.UpdateGameServerClusterRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_game_server_cluster_from_dict(): + test_update_game_server_cluster(request_type=dict) + + +@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", + request_type=game_server_clusters.PreviewUpdateGameServerClusterRequest, +): + 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 = request_type() + + # 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] == game_server_clusters.PreviewUpdateGameServerClusterRequest() + + # 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_from_dict(): + test_preview_update_game_server_cluster(request_type=dict) + + +@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. + with mock.patch( + "google.cloud.gaming_v1beta.services.game_server_clusters_service.transports.GameServerClustersServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + 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, mock.patch( + "google.cloud.gaming_v1beta.services.game_server_clusters_service.transports.GameServerClustersServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.GameServerClustersServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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",), + quota_project_id=None, + ) + + +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", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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_v1beta/test_game_server_configs_service.py b/tests/unit/gapic/gaming_v1beta/test_game_server_configs_service.py new file mode 100644 index 00000000..90e4939b --- /dev/null +++ b/tests/unit/gapic/gaming_v1beta/test_game_server_configs_service.py @@ -0,0 +1,1817 @@ +# -*- 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_v1beta.services.game_server_configs_service import ( + GameServerConfigsServiceAsyncClient, +) +from google.cloud.gaming_v1beta.services.game_server_configs_service import ( + GameServerConfigsServiceClient, +) +from google.cloud.gaming_v1beta.services.game_server_configs_service import pagers +from google.cloud.gaming_v1beta.services.game_server_configs_service import transports +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", + ), + ], +) +@mock.patch.object( + GameServerConfigsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerConfigsServiceClient), +) +@mock.patch.object( + GameServerConfigsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerConfigsServiceAsyncClient), +) +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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@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, + quota_project_id=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, + quota_project_id=None, + ) + + +def test_game_server_configs_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.gaming_v1beta.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, + quota_project_id=None, + ) + + +def test_list_game_server_configs( + transport: str = "grpc", + request_type=game_server_configs.ListGameServerConfigsRequest, +): + 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 = request_type() + + # 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] == game_server_configs.ListGameServerConfigsRequest() + + # 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_from_dict(): + test_list_game_server_configs(request_type=dict) + + +@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", request_type=game_server_configs.GetGameServerConfigRequest +): + 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 = request_type() + + # 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] == game_server_configs.GetGameServerConfigRequest() + + # 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_from_dict(): + test_get_game_server_config(request_type=dict) + + +@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", + request_type=game_server_configs.CreateGameServerConfigRequest, +): + 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 = request_type() + + # 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] == game_server_configs.CreateGameServerConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_game_server_config_from_dict(): + test_create_game_server_config(request_type=dict) + + +@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", + request_type=game_server_configs.DeleteGameServerConfigRequest, +): + 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 = request_type() + + # 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] == game_server_configs.DeleteGameServerConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_game_server_config_from_dict(): + test_delete_game_server_config(request_type=dict) + + +@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. + with mock.patch( + "google.cloud.gaming_v1beta.services.game_server_configs_service.transports.GameServerConfigsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + 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, mock.patch( + "google.cloud.gaming_v1beta.services.game_server_configs_service.transports.GameServerConfigsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.GameServerConfigsServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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",), + quota_project_id=None, + ) + + +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", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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_v1beta/test_game_server_deployments_service.py b/tests/unit/gapic/gaming_v1beta/test_game_server_deployments_service.py new file mode 100644 index 00000000..1009a7b4 --- /dev/null +++ b/tests/unit/gapic/gaming_v1beta/test_game_server_deployments_service.py @@ -0,0 +1,2886 @@ +# -*- 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_v1beta.services.game_server_deployments_service import ( + GameServerDeploymentsServiceAsyncClient, +) +from google.cloud.gaming_v1beta.services.game_server_deployments_service import ( + GameServerDeploymentsServiceClient, +) +from google.cloud.gaming_v1beta.services.game_server_deployments_service import pagers +from google.cloud.gaming_v1beta.services.game_server_deployments_service import ( + transports, +) +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", + ), + ], +) +@mock.patch.object( + GameServerDeploymentsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerDeploymentsServiceClient), +) +@mock.patch.object( + GameServerDeploymentsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GameServerDeploymentsServiceAsyncClient), +) +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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@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, + quota_project_id=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, + quota_project_id=None, + ) + + +def test_game_server_deployments_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.gaming_v1beta.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, + quota_project_id=None, + ) + + +def test_list_game_server_deployments( + transport: str = "grpc", + request_type=game_server_deployments.ListGameServerDeploymentsRequest, +): + 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 = request_type() + + # 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] == game_server_deployments.ListGameServerDeploymentsRequest() + + # 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_from_dict(): + test_list_game_server_deployments(request_type=dict) + + +@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", + request_type=game_server_deployments.GetGameServerDeploymentRequest, +): + 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 = request_type() + + # 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] == game_server_deployments.GetGameServerDeploymentRequest() + + # 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_from_dict(): + test_get_game_server_deployment(request_type=dict) + + +@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", + request_type=game_server_deployments.CreateGameServerDeploymentRequest, +): + 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 = request_type() + + # 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] == game_server_deployments.CreateGameServerDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_game_server_deployment_from_dict(): + test_create_game_server_deployment(request_type=dict) + + +@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", + request_type=game_server_deployments.DeleteGameServerDeploymentRequest, +): + 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 = request_type() + + # 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] == game_server_deployments.DeleteGameServerDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_game_server_deployment_from_dict(): + test_delete_game_server_deployment(request_type=dict) + + +@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", + request_type=game_server_deployments.UpdateGameServerDeploymentRequest, +): + 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 = request_type() + + # 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] == game_server_deployments.UpdateGameServerDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_game_server_deployment_from_dict(): + test_update_game_server_deployment(request_type=dict) + + +@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", + request_type=game_server_deployments.GetGameServerDeploymentRolloutRequest, +): + 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 = request_type() + + # 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] == game_server_deployments.GetGameServerDeploymentRolloutRequest() + ) + + # 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_from_dict(): + test_get_game_server_deployment_rollout(request_type=dict) + + +@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", + request_type=game_server_deployments.UpdateGameServerDeploymentRolloutRequest, +): + 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 = request_type() + + # 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] + == game_server_deployments.UpdateGameServerDeploymentRolloutRequest() + ) + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_game_server_deployment_rollout_from_dict(): + test_update_game_server_deployment_rollout(request_type=dict) + + +@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", + request_type=game_server_deployments.PreviewGameServerDeploymentRolloutRequest, +): + 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 = request_type() + + # 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] + == game_server_deployments.PreviewGameServerDeploymentRolloutRequest() + ) + + # 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_from_dict(): + test_preview_game_server_deployment_rollout(request_type=dict) + + +@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", + request_type=game_server_deployments.FetchDeploymentStateRequest, +): + 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 = request_type() + + # 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] == game_server_deployments.FetchDeploymentStateRequest() + + # 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_from_dict(): + test_fetch_deployment_state(request_type=dict) + + +@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. + with mock.patch( + "google.cloud.gaming_v1beta.services.game_server_deployments_service.transports.GameServerDeploymentsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + 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, mock.patch( + "google.cloud.gaming_v1beta.services.game_server_deployments_service.transports.GameServerDeploymentsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.GameServerDeploymentsServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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",), + quota_project_id=None, + ) + + +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", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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_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/gapic/gaming_v1beta/test_realms_service.py b/tests/unit/gapic/gaming_v1beta/test_realms_service.py new file mode 100644 index 00000000..3a120bd1 --- /dev/null +++ b/tests/unit/gapic/gaming_v1beta/test_realms_service.py @@ -0,0 +1,1971 @@ +# -*- 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_v1beta.services.realms_service import RealmsServiceAsyncClient +from google.cloud.gaming_v1beta.services.realms_service import RealmsServiceClient +from google.cloud.gaming_v1beta.services.realms_service import pagers +from google.cloud.gaming_v1beta.services.realms_service import transports +from google.cloud.gaming_v1beta.types import common +from google.cloud.gaming_v1beta.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" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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", + ), + ], +) +@mock.patch.object( + RealmsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RealmsServiceClient), +) +@mock.patch.object( + RealmsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RealmsServiceAsyncClient), +) +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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(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, + quota_project_id=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. + with mock.patch.dict(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, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@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, + quota_project_id=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, + quota_project_id=None, + ) + + +def test_realms_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.gaming_v1beta.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, + quota_project_id=None, + ) + + +def test_list_realms(transport: str = "grpc", request_type=realms.ListRealmsRequest): + 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 = request_type() + + # 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] == realms.ListRealmsRequest() + + # 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_from_dict(): + test_list_realms(request_type=dict) + + +@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", request_type=realms.GetRealmRequest): + 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 = request_type() + + # 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] == realms.GetRealmRequest() + + # 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_from_dict(): + test_get_realm(request_type=dict) + + +@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", request_type=realms.CreateRealmRequest): + 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 = request_type() + + # 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] == realms.CreateRealmRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_realm_from_dict(): + test_create_realm(request_type=dict) + + +@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", request_type=realms.DeleteRealmRequest): + 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 = request_type() + + # 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] == realms.DeleteRealmRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_realm_from_dict(): + test_delete_realm(request_type=dict) + + +@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", request_type=realms.UpdateRealmRequest): + 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 = request_type() + + # 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] == realms.UpdateRealmRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_realm_from_dict(): + test_update_realm(request_type=dict) + + +@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", request_type=realms.PreviewRealmUpdateRequest +): + 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 = request_type() + + # 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] == realms.PreviewRealmUpdateRequest() + + # 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_from_dict(): + test_preview_realm_update(request_type=dict) + + +@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. + with mock.patch( + "google.cloud.gaming_v1beta.services.realms_service.transports.RealmsServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + 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, mock.patch( + "google.cloud.gaming_v1beta.services.realms_service.transports.RealmsServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RealmsServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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",), + quota_project_id=None, + ) + + +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", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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, + quota_project_id=None, + ) + 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