diff --git a/.flake8 b/.flake8
index 49e82698..ed931638 100644
--- a/.flake8
+++ b/.flake8
@@ -16,11 +16,13 @@
# Generated by synthtool. DO NOT EDIT!
[flake8]
-ignore = E203, E266, E501, W503, F401, F841
+ignore = E203, E266, E501, W503
exclude =
# Exclude generated code.
**/proto/**
**/gapic/**
+ **/services/**
+ **/types/**
*_pb2.py
# Standard linting exemptions.
diff --git a/.gitignore b/.gitignore
index 3fb06e09..b9daa52f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,7 @@
dist
build
eggs
+.eggs
parts
bin
var
@@ -45,14 +46,16 @@ pip-log.txt
# Built documentation
docs/_build
bigquery/docs/generated
+docs.metadata
# Virtual environment
env/
coverage.xml
+sponge_log.xml
# System test environment variables.
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 6c4d1501..5bb320fc 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 32cb8dae..954dc789 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-bigquery-reservation/.kokoro/trampoline.sh"
+build_file: "python-bigquery-reservation/.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 c898ec4a..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-bigquery-reservation
-
-# 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/samples/lint/common.cfg b/.kokoro/samples/lint/common.cfg
new file mode 100644
index 00000000..e65f99c0
--- /dev/null
+++ b/.kokoro/samples/lint/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "lint"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-bigquery-reservation/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-bigquery-reservation/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/lint/continuous.cfg b/.kokoro/samples/lint/continuous.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/lint/continuous.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/lint/periodic.cfg b/.kokoro/samples/lint/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/lint/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/lint/presubmit.cfg b/.kokoro/samples/lint/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/lint/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg
new file mode 100644
index 00000000..b321611f
--- /dev/null
+++ b/.kokoro/samples/python3.6/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.6"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-bigquery-reservation/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-bigquery-reservation/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.6/continuous.cfg b/.kokoro/samples/python3.6/continuous.cfg
new file mode 100644
index 00000000..7218af14
--- /dev/null
+++ b/.kokoro/samples/python3.6/continuous.cfg
@@ -0,0 +1,7 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
+
diff --git a/.kokoro/samples/python3.6/periodic.cfg b/.kokoro/samples/python3.6/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/python3.6/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.6/presubmit.cfg b/.kokoro/samples/python3.6/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.6/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg
new file mode 100644
index 00000000..9de5da10
--- /dev/null
+++ b/.kokoro/samples/python3.7/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.7"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-bigquery-reservation/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-bigquery-reservation/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/continuous.cfg b/.kokoro/samples/python3.7/continuous.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.7/continuous.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/periodic.cfg b/.kokoro/samples/python3.7/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/python3.7/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.7/presubmit.cfg b/.kokoro/samples/python3.7/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.7/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg
new file mode 100644
index 00000000..bd5e76ee
--- /dev/null
+++ b/.kokoro/samples/python3.8/common.cfg
@@ -0,0 +1,34 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.8"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-bigquery-reservation/.kokoro/test-samples.sh"
+}
+
+# Configure the docker image for kokoro-trampoline.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker"
+}
+
+# Download secrets for samples
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples"
+
+# Download trampoline resources.
+gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
+
+# Use the trampoline script to run in docker.
+build_file: "python-bigquery-reservation/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/continuous.cfg b/.kokoro/samples/python3.8/continuous.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.8/continuous.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/periodic.cfg b/.kokoro/samples/python3.8/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/python3.8/periodic.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "False"
+}
\ No newline at end of file
diff --git a/.kokoro/samples/python3.8/presubmit.cfg b/.kokoro/samples/python3.8/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.8/presubmit.cfg
@@ -0,0 +1,6 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
\ No newline at end of file
diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh
new file mode 100755
index 00000000..969b5e61
--- /dev/null
+++ b/.kokoro/test-samples.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+# `-e` enables the script to automatically fail when a command fails
+# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero
+set -eo pipefail
+# Enables `**` to include files nested inside sub-folders
+shopt -s globstar
+
+cd github/python-bigquery-reservation
+
+# Run periodic samples tests at latest release
+if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then
+ LATEST_RELEASE=$(git describe --abbrev=0 --tags)
+ git checkout $LATEST_RELEASE
+fi
+
+# Disable buffering, so that the logs stream through.
+export PYTHONUNBUFFERED=1
+
+# Debug: show build environment
+env | grep KOKORO
+
+# Install nox
+python3.6 -m pip install --upgrade --quiet nox
+
+# Use secrets acessor service account to get secrets
+if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then
+ gcloud auth activate-service-account \
+ --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \
+ --project="cloud-devrel-kokoro-resources"
+fi
+
+# This script will create 3 files:
+# - testing/test-env.sh
+# - testing/service-account.json
+# - testing/client-secrets.json
+./scripts/decrypt-secrets.sh
+
+source ./testing/test-env.sh
+export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json
+
+# For cloud-run session, we activate the service account for gcloud sdk.
+gcloud auth activate-service-account \
+ --key-file "${GOOGLE_APPLICATION_CREDENTIALS}"
+
+export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json
+
+echo -e "\n******************** TESTING PROJECTS ********************"
+
+# Switch to 'fail at end' to allow all tests to complete before exiting.
+set +e
+# Use RTN to return a non-zero value if the test fails.
+RTN=0
+ROOT=$(pwd)
+# Find all requirements.txt in the samples directory (may break on whitespace).
+for file in samples/**/requirements.txt; do
+ cd "$ROOT"
+ # Navigate to the project folder.
+ file=$(dirname "$file")
+ cd "$file"
+
+ echo "------------------------------------------------------------"
+ echo "- testing $file"
+ echo "------------------------------------------------------------"
+
+ # Use nox to execute the tests for the project.
+ python3.6 -m nox -s "$RUN_TESTS_SESSION"
+ EXIT=$?
+
+ # If this is a periodic build, send the test log to the Build Cop Bot.
+ # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/buildcop.
+ if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then
+ chmod +x $KOKORO_GFILE_DIR/linux_amd64/buildcop
+ $KOKORO_GFILE_DIR/linux_amd64/buildcop
+ fi
+
+ if [[ $EXIT -ne 0 ]]; then
+ RTN=1
+ echo -e "\n Testing failed: Nox returned a non-zero exit code. \n"
+ else
+ echo -e "\n Testing completed.\n"
+ fi
+
+done
+cd "$ROOT"
+
+# Workaround for Kokoro permissions issue: delete secrets
+rm testing/{test-env.sh,client-secrets.json,service-account.json}
+
+exit "$RTN"
\ No newline at end of file
diff --git a/.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/MANIFEST.in b/MANIFEST.in
index 68855abc..e9e29d12 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -20,3 +20,6 @@ recursive-include google *.json *.proto
recursive-include tests *
global-exclude *.py[co]
global-exclude __pycache__
+
+# Exclude scripts for samples readmegen
+prune scripts/readme-gen
\ No newline at end of file
diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html
index 228529ef..6316a537 100644
--- a/docs/_templates/layout.html
+++ b/docs/_templates/layout.html
@@ -21,8 +21,8 @@
- On January 1, 2020 this library will no longer support Python 2 on the latest released version.
- Previously released library versions will continue to be available. For more information please
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version.
+ Library versions released prior to that date will continue to be available. For more information please
visit
Python 2 support on Google Cloud.
{% block body %} {% endblock %}
diff --git a/docs/conf.py b/docs/conf.py
index 75044379..18c52397 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 ------------------------------------------------
@@ -43,7 +47,7 @@
# autodoc/autosummary flags
autoclass_content = "both"
-autodoc_default_flags = ["members"]
+autodoc_default_options = {"members": True}
autosummary_generate = True
@@ -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.
@@ -337,7 +346,7 @@
intersphinx_mapping = {
"python": ("http://python.readthedocs.org/en/latest/", None),
"google-auth": ("https://google-auth.readthedocs.io/en/stable", None),
- "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None),
+ "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,),
"grpc": ("https://grpc.io/grpc/python/", None),
}
diff --git a/docs/reservation_v1/services.rst b/docs/reservation_v1/services.rst
index d941dc79..d573d08d 100644
--- a/docs/reservation_v1/services.rst
+++ b/docs/reservation_v1/services.rst
@@ -1,6 +1,6 @@
-Client for Google Cloud Bigquery Reservation API
-================================================
+Services for Google Cloud Bigquery Reservation v1 API
+=====================================================
-.. automodule:: google.cloud.bigquery.reservation_v1
+.. automodule:: google.cloud.bigquery.reservation_v1.services.reservation_service
:members:
:inherited-members:
diff --git a/docs/reservation_v1/types.rst b/docs/reservation_v1/types.rst
index 0713e115..b89970ad 100644
--- a/docs/reservation_v1/types.rst
+++ b/docs/reservation_v1/types.rst
@@ -1,5 +1,5 @@
-Types for Google Cloud Bigquery Reservation API
-===============================================
+Types for Google Cloud Bigquery Reservation v1 API
+==================================================
.. automodule:: google.cloud.bigquery.reservation_v1.types
:members:
diff --git a/google/cloud/bigquery/reservation/__init__.py b/google/cloud/bigquery/reservation/__init__.py
index 315f992a..74fa58e2 100644
--- a/google/cloud/bigquery/reservation/__init__.py
+++ b/google/cloud/bigquery/reservation/__init__.py
@@ -15,7 +15,9 @@
# limitations under the License.
#
-
+from google.cloud.bigquery.reservation_v1.services.reservation_service.async_client import (
+ ReservationServiceAsyncClient,
+)
from google.cloud.bigquery.reservation_v1.services.reservation_service.client import (
ReservationServiceClient,
)
@@ -114,6 +116,7 @@
"MergeCapacityCommitmentsRequest",
"MoveAssignmentRequest",
"Reservation",
+ "ReservationServiceAsyncClient",
"ReservationServiceClient",
"SearchAssignmentsRequest",
"SearchAssignmentsResponse",
diff --git a/google/cloud/bigquery/reservation_v1/__init__.py b/google/cloud/bigquery/reservation_v1/__init__.py
index 32718652..804db281 100644
--- a/google/cloud/bigquery/reservation_v1/__init__.py
+++ b/google/cloud/bigquery/reservation_v1/__init__.py
@@ -15,7 +15,6 @@
# limitations under the License.
#
-
from .services.reservation_service import ReservationServiceClient
from .types.reservation import Assignment
from .types.reservation import BiReservation
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/__init__.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/__init__.py
index 1c06ff0e..81e7a031 100644
--- a/google/cloud/bigquery/reservation_v1/services/reservation_service/__init__.py
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/__init__.py
@@ -16,5 +16,9 @@
#
from .client import ReservationServiceClient
+from .async_client import ReservationServiceAsyncClient
-__all__ = ("ReservationServiceClient",)
+__all__ = (
+ "ReservationServiceClient",
+ "ReservationServiceAsyncClient",
+)
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/async_client.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/async_client.py
new file mode 100644
index 00000000..632b4b75
--- /dev/null
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/async_client.py
@@ -0,0 +1,1819 @@
+# -*- 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.cloud.bigquery.reservation_v1.services.reservation_service import pagers
+from google.cloud.bigquery.reservation_v1.types import reservation
+from google.cloud.bigquery.reservation_v1.types import reservation as gcbr_reservation
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+from google.rpc import status_pb2 as status # type: ignore
+
+from .transports.base import ReservationServiceTransport
+from .transports.grpc_asyncio import ReservationServiceGrpcAsyncIOTransport
+from .client import ReservationServiceClient
+
+
+class ReservationServiceAsyncClient:
+ """This API allows users to manage their flat-rate BigQuery
+ reservations.
+
+ A reservation provides computational resource guarantees, in the
+ form of `slots
`__, to
+ users. A slot is a unit of computational power in BigQuery, and
+ serves as the basic unit of parallelism. In a scan of a
+ multi-partitioned table, a single slot operates on a single
+ partition of the table. A reservation resource exists as a child
+ resource of the admin project and location, e.g.:
+ ``projects/myproject/locations/US/reservations/reservationName``.
+
+ A capacity commitment is a way to purchase compute capacity for
+ BigQuery jobs (in the form of slots) with some committed period of
+ usage. A capacity commitment resource exists as a child resource of
+ the admin project and location, e.g.:
+ ``projects/myproject/locations/US/capacityCommitments/id``.
+ """
+
+ _client: ReservationServiceClient
+
+ DEFAULT_ENDPOINT = ReservationServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = ReservationServiceClient.DEFAULT_MTLS_ENDPOINT
+
+ assignment_path = staticmethod(ReservationServiceClient.assignment_path)
+
+ reservation_path = staticmethod(ReservationServiceClient.reservation_path)
+
+ bi_reservation_path = staticmethod(ReservationServiceClient.bi_reservation_path)
+
+ capacity_commitment_path = staticmethod(
+ ReservationServiceClient.capacity_commitment_path
+ )
+
+ from_service_account_file = ReservationServiceClient.from_service_account_file
+ from_service_account_json = from_service_account_file
+
+ get_transport_class = functools.partial(
+ type(ReservationServiceClient).get_transport_class,
+ type(ReservationServiceClient),
+ )
+
+ def __init__(
+ self,
+ *,
+ credentials: credentials.Credentials = None,
+ transport: Union[str, ReservationServiceTransport] = "grpc_asyncio",
+ client_options: ClientOptions = None,
+ ) -> None:
+ """Instantiate the reservation 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, ~.ReservationServiceTransport]): 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 = ReservationServiceClient(
+ credentials=credentials, transport=transport, client_options=client_options,
+ )
+
+ async def create_reservation(
+ self,
+ request: gcbr_reservation.CreateReservationRequest = None,
+ *,
+ parent: str = None,
+ reservation: gcbr_reservation.Reservation = None,
+ reservation_id: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> gcbr_reservation.Reservation:
+ r"""Creates a new reservation resource.
+
+ Args:
+ request (:class:`~.gcbr_reservation.CreateReservationRequest`):
+ The request object. The request for
+ [ReservationService.CreateReservation][google.cloud.bigquery.reservation.v1.ReservationService.CreateReservation].
+ parent (:class:`str`):
+ Required. Project, location. E.g.,
+ ``projects/myproject/locations/US``
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ reservation (:class:`~.gcbr_reservation.Reservation`):
+ Definition of the new reservation to
+ create.
+ This corresponds to the ``reservation`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ reservation_id (:class:`str`):
+ The reservation ID. This field must
+ only contain lower case alphanumeric
+ characters or dash. Max length is 64
+ characters.
+ This corresponds to the ``reservation_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:
+ ~.gcbr_reservation.Reservation:
+ A reservation is a mechanism used to
+ guarantee slots to users.
+
+ """
+ # 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, reservation, reservation_id]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = gcbr_reservation.CreateReservationRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if reservation is not None:
+ request.reservation = reservation
+ if reservation_id is not None:
+ request.reservation_id = reservation_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_reservation,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def list_reservations(
+ self,
+ request: reservation.ListReservationsRequest = None,
+ *,
+ parent: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListReservationsAsyncPager:
+ r"""Lists all the reservations for the project in the
+ specified location.
+
+ Args:
+ request (:class:`~.reservation.ListReservationsRequest`):
+ The request object. The request for
+ [ReservationService.ListReservations][google.cloud.bigquery.reservation.v1.ReservationService.ListReservations].
+ parent (:class:`str`):
+ Required. The parent resource name containing project
+ and location, e.g.: ``projects/myproject/locations/US``
+ 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.ListReservationsAsyncPager:
+ The response for
+ [ReservationService.ListReservations][google.cloud.bigquery.reservation.v1.ReservationService.ListReservations].
+
+ 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 = reservation.ListReservationsRequest(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_reservations,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.ListReservationsAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_reservation(
+ self,
+ request: reservation.GetReservationRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.Reservation:
+ r"""Returns information about the reservation.
+
+ Args:
+ request (:class:`~.reservation.GetReservationRequest`):
+ The request object. The request for
+ [ReservationService.GetReservation][google.cloud.bigquery.reservation.v1.ReservationService.GetReservation].
+ name (:class:`str`):
+ Required. Resource name of the reservation to retrieve.
+ E.g.,
+ ``projects/myproject/locations/US/reservations/team1-prod``
+ 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:
+ ~.reservation.Reservation:
+ A reservation is a mechanism used to
+ guarantee slots to users.
+
+ """
+ # 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 = reservation.GetReservationRequest(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_reservation,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def delete_reservation(
+ self,
+ request: reservation.DeleteReservationRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes a reservation. Returns
+ ``google.rpc.Code.FAILED_PRECONDITION`` when reservation has
+ assignments.
+
+ Args:
+ request (:class:`~.reservation.DeleteReservationRequest`):
+ The request object. The request for
+ [ReservationService.DeleteReservation][google.cloud.bigquery.reservation.v1.ReservationService.DeleteReservation].
+ name (:class:`str`):
+ Required. Resource name of the reservation to retrieve.
+ E.g.,
+ ``projects/myproject/locations/US/reservations/team1-prod``
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ 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 = reservation.DeleteReservationRequest(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_reservation,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ await rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
+
+ async def update_reservation(
+ self,
+ request: gcbr_reservation.UpdateReservationRequest = None,
+ *,
+ reservation: gcbr_reservation.Reservation = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> gcbr_reservation.Reservation:
+ r"""Updates an existing reservation resource.
+
+ Args:
+ request (:class:`~.gcbr_reservation.UpdateReservationRequest`):
+ The request object. The request for
+ [ReservationService.UpdateReservation][google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservation].
+ reservation (:class:`~.gcbr_reservation.Reservation`):
+ Content of the reservation to update.
+ This corresponds to the ``reservation`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Standard field mask for the set of
+ fields to be updated.
+ 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:
+ ~.gcbr_reservation.Reservation:
+ A reservation is a mechanism used to
+ guarantee slots to users.
+
+ """
+ # 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([reservation, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = gcbr_reservation.UpdateReservationRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if reservation is not None:
+ request.reservation = reservation
+ 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_reservation,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("reservation.name", request.reservation.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def create_capacity_commitment(
+ self,
+ request: reservation.CreateCapacityCommitmentRequest = None,
+ *,
+ parent: str = None,
+ capacity_commitment: reservation.CapacityCommitment = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.CapacityCommitment:
+ r"""Creates a new capacity commitment resource.
+
+ Args:
+ request (:class:`~.reservation.CreateCapacityCommitmentRequest`):
+ The request object. The request for
+ [ReservationService.CreateCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.CreateCapacityCommitment].
+ parent (:class:`str`):
+ Required. Resource name of the parent reservation. E.g.,
+ ``projects/myproject/locations/US``
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ capacity_commitment (:class:`~.reservation.CapacityCommitment`):
+ Content of the capacity commitment to
+ create.
+ This corresponds to the ``capacity_commitment`` 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:
+ ~.reservation.CapacityCommitment:
+ Capacity commitment is a way to
+ purchase compute capacity for BigQuery
+ jobs (in the form of slots) with some
+ committed period of usage. Annual
+ commitments renew by default.
+ Commitments can be removed after their
+ commitment end time passes.
+
+ In order to remove annual commitment,
+ its plan needs to be changed to monthly
+ or flex first.
+
+ A capacity commitment resource exists as
+ a child resource of the admin project.
+
+ """
+ # 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, capacity_commitment]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.CreateCapacityCommitmentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if capacity_commitment is not None:
+ request.capacity_commitment = capacity_commitment
+
+ # 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_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def list_capacity_commitments(
+ self,
+ request: reservation.ListCapacityCommitmentsRequest = None,
+ *,
+ parent: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListCapacityCommitmentsAsyncPager:
+ r"""Lists all the capacity commitments for the admin
+ project.
+
+ Args:
+ request (:class:`~.reservation.ListCapacityCommitmentsRequest`):
+ The request object. The request for
+ [ReservationService.ListCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.ListCapacityCommitments].
+ parent (:class:`str`):
+ Required. Resource name of the parent reservation. E.g.,
+ ``projects/myproject/locations/US``
+ 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.ListCapacityCommitmentsAsyncPager:
+ The response for
+ [ReservationService.ListCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.ListCapacityCommitments].
+
+ 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 = reservation.ListCapacityCommitmentsRequest(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_capacity_commitments,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.ListCapacityCommitmentsAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_capacity_commitment(
+ self,
+ request: reservation.GetCapacityCommitmentRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.CapacityCommitment:
+ r"""Returns information about the capacity commitment.
+
+ Args:
+ request (:class:`~.reservation.GetCapacityCommitmentRequest`):
+ The request object. The request for
+ [ReservationService.GetCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.GetCapacityCommitment].
+ name (:class:`str`):
+ Required. Resource name of the capacity commitment to
+ retrieve. E.g.,
+ ``projects/myproject/locations/US/capacityCommitments/123``
+ 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:
+ ~.reservation.CapacityCommitment:
+ Capacity commitment is a way to
+ purchase compute capacity for BigQuery
+ jobs (in the form of slots) with some
+ committed period of usage. Annual
+ commitments renew by default.
+ Commitments can be removed after their
+ commitment end time passes.
+
+ In order to remove annual commitment,
+ its plan needs to be changed to monthly
+ or flex first.
+
+ A capacity commitment resource exists as
+ a child resource of the admin project.
+
+ """
+ # 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 = reservation.GetCapacityCommitmentRequest(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_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def delete_capacity_commitment(
+ self,
+ request: reservation.DeleteCapacityCommitmentRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes a capacity commitment. Attempting to delete capacity
+ commitment before its commitment_end_time will fail with the
+ error code ``google.rpc.Code.FAILED_PRECONDITION``.
+
+ Args:
+ request (:class:`~.reservation.DeleteCapacityCommitmentRequest`):
+ The request object. The request for
+ [ReservationService.DeleteCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.DeleteCapacityCommitment].
+ name (:class:`str`):
+ Required. Resource name of the capacity commitment to
+ delete. E.g.,
+ ``projects/myproject/locations/US/capacityCommitments/123``
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ 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 = reservation.DeleteCapacityCommitmentRequest(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_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ await rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
+
+ async def update_capacity_commitment(
+ self,
+ request: reservation.UpdateCapacityCommitmentRequest = None,
+ *,
+ capacity_commitment: reservation.CapacityCommitment = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.CapacityCommitment:
+ r"""Updates an existing capacity commitment.
+
+ Only ``plan`` and ``renewal_plan`` fields can be updated.
+
+ Plan can only be changed to a plan of a longer commitment
+ period. Attempting to change to a plan with shorter commitment
+ period will fail with the error code
+ ``google.rpc.Code.FAILED_PRECONDITION``.
+
+ Args:
+ request (:class:`~.reservation.UpdateCapacityCommitmentRequest`):
+ The request object. The request for
+ [ReservationService.UpdateCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.UpdateCapacityCommitment].
+ capacity_commitment (:class:`~.reservation.CapacityCommitment`):
+ Content of the capacity commitment to
+ update.
+ This corresponds to the ``capacity_commitment`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Standard field mask for the set of
+ fields to be updated.
+ 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:
+ ~.reservation.CapacityCommitment:
+ Capacity commitment is a way to
+ purchase compute capacity for BigQuery
+ jobs (in the form of slots) with some
+ committed period of usage. Annual
+ commitments renew by default.
+ Commitments can be removed after their
+ commitment end time passes.
+
+ In order to remove annual commitment,
+ its plan needs to be changed to monthly
+ or flex first.
+
+ A capacity commitment resource exists as
+ a child resource of the admin project.
+
+ """
+ # 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([capacity_commitment, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.UpdateCapacityCommitmentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if capacity_commitment is not None:
+ request.capacity_commitment = capacity_commitment
+ 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_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("capacity_commitment.name", request.capacity_commitment.name),)
+ ),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def split_capacity_commitment(
+ self,
+ request: reservation.SplitCapacityCommitmentRequest = None,
+ *,
+ name: str = None,
+ slot_count: int = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.SplitCapacityCommitmentResponse:
+ r"""Splits capacity commitment to two commitments of the same plan
+ and ``commitment_end_time``.
+
+ A common use case is to enable downgrading commitments.
+
+ For example, in order to downgrade from 10000 slots to 8000, you
+ might split a 10000 capacity commitment into commitments of 2000
+ and 8000. Then, you would change the plan of the first one to
+ ``FLEX`` and then delete it.
+
+ Args:
+ request (:class:`~.reservation.SplitCapacityCommitmentRequest`):
+ The request object. The request for
+ [ReservationService.SplitCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.SplitCapacityCommitment].
+ name (:class:`str`):
+ Required. The resource name e.g.,:
+ ``projects/myproject/locations/US/capacityCommitments/123``
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ slot_count (:class:`int`):
+ Number of slots in the capacity
+ commitment after the split.
+ This corresponds to the ``slot_count`` 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:
+ ~.reservation.SplitCapacityCommitmentResponse:
+ The response for
+ [ReservationService.SplitCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.SplitCapacityCommitment].
+
+ """
+ # 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, slot_count]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.SplitCapacityCommitmentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+ if slot_count is not None:
+ request.slot_count = slot_count
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.split_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def merge_capacity_commitments(
+ self,
+ request: reservation.MergeCapacityCommitmentsRequest = None,
+ *,
+ parent: str = None,
+ capacity_commitment_ids: Sequence[str] = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.CapacityCommitment:
+ r"""Merges capacity commitments of the same plan into a single
+ commitment.
+
+ The resulting capacity commitment has the greater
+ commitment_end_time out of the to-be-merged capacity
+ commitments.
+
+ Attempting to merge capacity commitments of different plan will
+ fail with the error code
+ ``google.rpc.Code.FAILED_PRECONDITION``.
+
+ Args:
+ request (:class:`~.reservation.MergeCapacityCommitmentsRequest`):
+ The request object. The request for
+ [ReservationService.MergeCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.MergeCapacityCommitments].
+ parent (:class:`str`):
+ Parent resource that identifies admin project and
+ location e.g., ``projects/myproject/locations/us``
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ capacity_commitment_ids (:class:`Sequence[str]`):
+ Ids of capacity commitments to merge.
+ These capacity commitments must exist
+ under admin project and location
+ specified in the parent.
+ ID is the last portion of capacity
+ commitment name e.g., 'abc' for
+ projects/myproject/locations/US/capacityCommitments/abc
+ This corresponds to the ``capacity_commitment_ids`` 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:
+ ~.reservation.CapacityCommitment:
+ Capacity commitment is a way to
+ purchase compute capacity for BigQuery
+ jobs (in the form of slots) with some
+ committed period of usage. Annual
+ commitments renew by default.
+ Commitments can be removed after their
+ commitment end time passes.
+
+ In order to remove annual commitment,
+ its plan needs to be changed to monthly
+ or flex first.
+
+ A capacity commitment resource exists as
+ a child resource of the admin project.
+
+ """
+ # 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, capacity_commitment_ids]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.MergeCapacityCommitmentsRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if capacity_commitment_ids is not None:
+ request.capacity_commitment_ids = capacity_commitment_ids
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.merge_capacity_commitments,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def create_assignment(
+ self,
+ request: reservation.CreateAssignmentRequest = None,
+ *,
+ parent: str = None,
+ assignment: reservation.Assignment = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.Assignment:
+ r"""Creates an assignment object which allows the given project to
+ submit jobs of a certain type using slots from the specified
+ reservation.
+
+ Currently a resource (project, folder, organization) can only
+ have one assignment per each (job_type, location) combination,
+ and that reservation will be used for all jobs of the matching
+ type.
+
+ Different assignments can be created on different levels of the
+ projects, folders or organization hierarchy. During query
+ execution, the assignment is looked up at the project, folder
+ and organization levels in that order. The first assignment
+ found is applied to the query.
+
+ When creating assignments, it does not matter if other
+ assignments exist at higher levels.
+
+ Example:
+
+ - The organization ``organizationA`` contains two projects,
+ ``project1`` and ``project2``.
+ - Assignments for all three entities (``organizationA``,
+ ``project1``, and ``project2``) could all be created and
+ mapped to the same or different reservations.
+
+ Returns ``google.rpc.Code.PERMISSION_DENIED`` if user does not
+ have 'bigquery.admin' permissions on the project using the
+ reservation and the project that owns this reservation.
+
+ Returns ``google.rpc.Code.INVALID_ARGUMENT`` when location of
+ the assignment does not match location of the reservation.
+
+ Args:
+ request (:class:`~.reservation.CreateAssignmentRequest`):
+ The request object. The request for
+ [ReservationService.CreateAssignment][google.cloud.bigquery.reservation.v1.ReservationService.CreateAssignment].
+ Note: "bigquery.reservationAssignments.create"
+ permission is required on the related assignee.
+ parent (:class:`str`):
+ Required. The parent resource name of the assignment
+ E.g.
+ ``projects/myproject/locations/US/reservations/team1-prod``
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ assignment (:class:`~.reservation.Assignment`):
+ Assignment resource to create.
+ This corresponds to the ``assignment`` 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:
+ ~.reservation.Assignment:
+ A Assignment allows a project to
+ submit jobs of a certain type using
+ slots from the specified reservation.
+
+ """
+ # 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, assignment]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.CreateAssignmentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if assignment is not None:
+ request.assignment = assignment
+
+ # 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_assignment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def list_assignments(
+ self,
+ request: reservation.ListAssignmentsRequest = None,
+ *,
+ parent: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.ListAssignmentsAsyncPager:
+ r"""Lists assignments.
+
+ Only explicitly created assignments will be returned.
+
+ Example:
+
+ - Organization ``organizationA`` contains two projects,
+ ``project1`` and ``project2``.
+ - Reservation ``res1`` exists and was created previously.
+ - CreateAssignment was used previously to define the following
+ associations between entities and reservations:
+ ```` and ````
+
+ In this example, ListAssignments will just return the above two
+ assignments for reservation ``res1``, and no expansion/merge
+ will happen.
+
+ The wildcard "-" can be used for reservations in the request. In
+ that case all assignments belongs to the specified project and
+ location will be listed.
+
+ **Note** "-" cannot be used for projects nor locations.
+
+ Args:
+ request (:class:`~.reservation.ListAssignmentsRequest`):
+ The request object. The request for
+ [ReservationService.ListAssignments][google.cloud.bigquery.reservation.v1.ReservationService.ListAssignments].
+ parent (:class:`str`):
+ Required. The parent resource name e.g.:
+
+ ``projects/myproject/locations/US/reservations/team1-prod``
+
+ Or:
+
+ ``projects/myproject/locations/US/reservations/-``
+ 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.ListAssignmentsAsyncPager:
+ The response for
+ [ReservationService.ListAssignments][google.cloud.bigquery.reservation.v1.ReservationService.ListAssignments].
+
+ 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 = reservation.ListAssignmentsRequest(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_assignments,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.ListAssignmentsAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def delete_assignment(
+ self,
+ request: reservation.DeleteAssignmentRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes a assignment. No expansion will happen.
+
+ Example:
+
+ - Organization ``organizationA`` contains two projects,
+ ``project1`` and ``project2``.
+ - Reservation ``res1`` exists and was created previously.
+ - CreateAssignment was used previously to define the following
+ associations between entities and reservations:
+ ```` and ````
+
+ In this example, deletion of the ````
+ assignment won't affect the other assignment
+ ````. After said deletion, queries from
+ ``project1`` will still use ``res1`` while queries from
+ ``project2`` will switch to use on-demand mode.
+
+ Args:
+ request (:class:`~.reservation.DeleteAssignmentRequest`):
+ The request object. The request for
+ [ReservationService.DeleteAssignment][google.cloud.bigquery.reservation.v1.ReservationService.DeleteAssignment].
+ Note: "bigquery.reservationAssignments.delete"
+ permission is required on the related assignee.
+ name (:class:`str`):
+ Required. Name of the resource, e.g.
+ ``projects/myproject/locations/US/reservations/team1-prod/assignments/123``
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ 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 = reservation.DeleteAssignmentRequest(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_assignment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ await rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
+
+ async def search_assignments(
+ self,
+ request: reservation.SearchAssignmentsRequest = None,
+ *,
+ parent: str = None,
+ query: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> pagers.SearchAssignmentsAsyncPager:
+ r"""Looks up assignments for a specified resource for a particular
+ region. If the request is about a project:
+
+ 1. Assignments created on the project will be returned if they
+ exist.
+ 2. Otherwise assignments created on the closest ancestor will be
+ returned.
+ 3. Assignments for different JobTypes will all be returned.
+
+ The same logic applies if the request is about a folder.
+
+ If the request is about an organization, then assignments
+ created on the organization will be returned (organization
+ doesn't have ancestors).
+
+ Comparing to ListAssignments, there are some behavior
+ differences:
+
+ 1. permission on the assignee will be verified in this API.
+ 2. Hierarchy lookup (project->folder->organization) happens in
+ this API.
+ 3. Parent here is ``projects/*/locations/*``, instead of
+ ``projects/*/locations/*reservations/*``.
+
+ **Note** "-" cannot be used for projects nor locations.
+
+ Args:
+ request (:class:`~.reservation.SearchAssignmentsRequest`):
+ The request object. The request for
+ [ReservationService.SearchAssignments][google.cloud.bigquery.reservation.v1.ReservationService.SearchAssignments].
+ Note: "bigquery.reservationAssignments.search"
+ permission is required on the related assignee.
+ parent (:class:`str`):
+ Required. The resource name of the admin
+ project(containing project and location), e.g.:
+ ``projects/myproject/locations/US``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ query (:class:`str`):
+ Please specify resource name as assignee in the query.
+
+ Examples:
+
+ - ``assignee=projects/myproject``
+ - ``assignee=folders/123``
+ - ``assignee=organizations/456``
+
+ This corresponds to the ``query`` 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.SearchAssignmentsAsyncPager:
+ The response for
+ [ReservationService.SearchAssignments][google.cloud.bigquery.reservation.v1.ReservationService.SearchAssignments].
+
+ 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, query]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.SearchAssignmentsRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if query is not None:
+ request.query = query
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.search_assignments,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # This method is paged; wrap the response in a pager, which provides
+ # an `__aiter__` convenience method.
+ response = pagers.SearchAssignmentsAsyncPager(
+ method=rpc, request=request, response=response, metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def move_assignment(
+ self,
+ request: reservation.MoveAssignmentRequest = None,
+ *,
+ name: str = None,
+ destination_id: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.Assignment:
+ r"""Moves an assignment under a new reservation.
+ This differs from removing an existing assignment and
+ recreating a new one by providing a transactional change
+ that ensures an assignee always has an associated
+ reservation.
+
+ Args:
+ request (:class:`~.reservation.MoveAssignmentRequest`):
+ The request object. The request for
+ [ReservationService.MoveAssignment][google.cloud.bigquery.reservation.v1.ReservationService.MoveAssignment].
+ **Note**: "bigquery.reservationAssignments.create"
+ permission is required on the destination_id.
+
+ **Note**: "bigquery.reservationAssignments.create" and
+ "bigquery.reservationAssignments.delete" permission are
+ required on the related assignee.
+ name (:class:`str`):
+ Required. The resource name of the assignment, e.g.
+ ``projects/myproject/locations/US/reservations/team1-prod/assignments/123``
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ destination_id (:class:`str`):
+ The new reservation ID, e.g.:
+ ``projects/myotherproject/locations/US/reservations/team2-prod``
+ This corresponds to the ``destination_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:
+ ~.reservation.Assignment:
+ A Assignment allows a project to
+ submit jobs of a certain type using
+ slots from the specified reservation.
+
+ """
+ # 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, destination_id]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.MoveAssignmentRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+ if destination_id is not None:
+ request.destination_id = destination_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.move_assignment,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def get_bi_reservation(
+ self,
+ request: reservation.GetBiReservationRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.BiReservation:
+ r"""Retrieves a BI reservation.
+
+ Args:
+ request (:class:`~.reservation.GetBiReservationRequest`):
+ The request object. A request to get a singleton BI
+ reservation.
+ name (:class:`str`):
+ Required. Name of the requested reservation, for
+ example:
+ ``projects/{project_id}/locations/{location_id}/bireservation``
+ 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:
+ ~.reservation.BiReservation:
+ Represents a BI Reservation.
+ """
+ # 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 = reservation.GetBiReservationRequest(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_bi_reservation,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def update_bi_reservation(
+ self,
+ request: reservation.UpdateBiReservationRequest = None,
+ *,
+ bi_reservation: reservation.BiReservation = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> reservation.BiReservation:
+ r"""Updates a BI reservation.
+
+ Only fields specified in the ``field_mask`` are updated.
+
+ A singleton BI reservation always exists with default size 0. In
+ order to reserve BI capacity it needs to be updated to an amount
+ greater than 0. In order to release BI capacity reservation size
+ must be set to 0.
+
+ Args:
+ request (:class:`~.reservation.UpdateBiReservationRequest`):
+ The request object. A request to update a BI
+ reservation.
+ bi_reservation (:class:`~.reservation.BiReservation`):
+ A reservation to update.
+ This corresponds to the ``bi_reservation`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ A list of fields to be updated in
+ this request.
+ 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:
+ ~.reservation.BiReservation:
+ Represents a BI Reservation.
+ """
+ # 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([bi_reservation, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = reservation.UpdateBiReservationRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if bi_reservation is not None:
+ request.bi_reservation = bi_reservation
+ 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_bi_reservation,
+ default_timeout=None,
+ client_info=_client_info,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("bi_reservation.name", request.bi_reservation.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-bigquery-reservation",
+ ).version,
+ )
+except pkg_resources.DistributionNotFound:
+ _client_info = gapic_v1.client_info.ClientInfo()
+
+
+__all__ = ("ReservationServiceAsyncClient",)
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/client.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/client.py
index 5a1c0941..2b3d75be 100644
--- a/google/cloud/bigquery/reservation_v1/services/reservation_service/client.py
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/client.py
@@ -16,6 +16,7 @@
#
from collections import OrderedDict
+import os
import re
from typing import Callable, Dict, Sequence, Tuple, Type, Union
import pkg_resources
@@ -25,6 +26,8 @@
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.cloud.bigquery.reservation_v1.services.reservation_service import pagers
@@ -36,6 +39,7 @@
from .transports.base import ReservationServiceTransport
from .transports.grpc import ReservationServiceGrpcTransport
+from .transports.grpc_asyncio import ReservationServiceGrpcAsyncIOTransport
class ReservationServiceClientMeta(type):
@@ -50,9 +54,10 @@ class ReservationServiceClientMeta(type):
OrderedDict()
) # type: Dict[str, Type[ReservationServiceTransport]]
_transport_registry["grpc"] = ReservationServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = ReservationServiceGrpcAsyncIOTransport
def get_transport_class(
- cls, label: str = None
+ cls, label: str = None,
) -> Type[ReservationServiceTransport]:
"""Return an appropriate transport class.
@@ -147,72 +152,72 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
from_service_account_json = from_service_account_file
@staticmethod
- def capacity_commitment_path(
- project: str, location: str, capacity_commitment: str
+ def assignment_path(
+ project: str, location: str, reservation: str, assignment: str,
) -> str:
- """Return a fully-qualified capacity_commitment string."""
- return "projects/{project}/locations/{location}/capacityCommitments/{capacity_commitment}".format(
- project=project, location=location, capacity_commitment=capacity_commitment
+ """Return a fully-qualified assignment string."""
+ return "projects/{project}/locations/{location}/reservations/{reservation}/assignments/{assignment}".format(
+ project=project,
+ location=location,
+ reservation=reservation,
+ assignment=assignment,
)
@staticmethod
- def parse_capacity_commitment_path(path: str) -> Dict[str, str]:
- """Parse a capacity_commitment path into its component segments."""
+ def parse_assignment_path(path: str) -> Dict[str, str]:
+ """Parse a assignment path into its component segments."""
m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/capacityCommitments/(?P.+?)$",
+ r"^projects/(?P.+?)/locations/(?P.+?)/reservations/(?P.+?)/assignments/(?P.+?)$",
path,
)
return m.groupdict() if m else {}
@staticmethod
- def reservation_path(project: str, location: str, reservation: str) -> str:
- """Return a fully-qualified reservation string."""
- return "projects/{project}/locations/{location}/reservations/{reservation}".format(
- project=project, location=location, reservation=reservation
+ def bi_reservation_path(project: str, location: str,) -> str:
+ """Return a fully-qualified bi_reservation string."""
+ return "projects/{project}/locations/{location}/bireservation".format(
+ project=project, location=location,
)
@staticmethod
- def parse_reservation_path(path: str) -> Dict[str, str]:
- """Parse a reservation path into its component segments."""
+ def parse_bi_reservation_path(path: str) -> Dict[str, str]:
+ """Parse a bi_reservation path into its component segments."""
m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/reservations/(?P.+?)$",
+ r"^projects/(?P.+?)/locations/(?P.+?)/bireservation$",
path,
)
return m.groupdict() if m else {}
@staticmethod
- def bi_reservation_path(project: str, location: str) -> str:
- """Return a fully-qualified bi_reservation string."""
- return "projects/{project}/locations/{location}/bireservation".format(
- project=project, location=location
+ def capacity_commitment_path(
+ project: str, location: str, capacity_commitment: str,
+ ) -> str:
+ """Return a fully-qualified capacity_commitment string."""
+ return "projects/{project}/locations/{location}/capacityCommitments/{capacity_commitment}".format(
+ project=project, location=location, capacity_commitment=capacity_commitment,
)
@staticmethod
- def parse_bi_reservation_path(path: str) -> Dict[str, str]:
- """Parse a bi_reservation path into its component segments."""
+ def parse_capacity_commitment_path(path: str) -> Dict[str, str]:
+ """Parse a capacity_commitment path into its component segments."""
m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/bireservation$",
+ r"^projects/(?P.+?)/locations/(?P.+?)/capacityCommitments/(?P.+?)$",
path,
)
return m.groupdict() if m else {}
@staticmethod
- def assignment_path(
- project: str, location: str, reservation: str, assignment: str
- ) -> str:
- """Return a fully-qualified assignment string."""
- return "projects/{project}/locations/{location}/reservations/{reservation}/assignments/{assignment}".format(
- project=project,
- location=location,
- reservation=reservation,
- assignment=assignment,
+ def reservation_path(project: str, location: str, reservation: str,) -> str:
+ """Return a fully-qualified reservation string."""
+ return "projects/{project}/locations/{location}/reservations/{reservation}".format(
+ project=project, location=location, reservation=reservation,
)
@staticmethod
- def parse_assignment_path(path: str) -> Dict[str, str]:
- """Parse a assignment path into its component segments."""
+ def parse_reservation_path(path: str) -> Dict[str, str]:
+ """Parse a reservation path into its component segments."""
m = re.match(
- r"^projects/(?P.+?)/locations/(?P.+?)/reservations/(?P.+?)/assignments/(?P.+?)$",
+ r"^projects/(?P.+?)/locations/(?P.+?)/reservations/(?P.+?)$",
path,
)
return m.groupdict() if m else {}
@@ -235,66 +240,76 @@ def __init__(
transport (Union[str, ~.ReservationServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (ClientOptions): Custom options for the client.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
- default endpoint provided by the client.
- (2) If ``transport`` argument is None, ``client_options`` can be
- used to create a mutual TLS transport. If ``client_cert_source``
- is provided, mutual TLS transport will be created with the given
- ``api_endpoint`` or the default mTLS endpoint, and the client
- SSL credentials obtained from ``client_cert_source``.
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint, this is the default value for
+ the environment variable) and "auto" (auto switch to the default
+ mTLS endpoint if client SSL credentials is present). However,
+ the ``api_endpoint`` property takes precedence if provided.
+ (2) The ``client_cert_source`` property is used to provide client
+ SSL credentials for mutual TLS transport. If not provided, the
+ default SSL credentials will be used if present.
Raises:
- google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = ClientOptions.from_dict(client_options)
+ if client_options is None:
+ client_options = ClientOptions.ClientOptions()
+
+ if client_options.api_endpoint is None:
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never")
+ if use_mtls_env == "never":
+ client_options.api_endpoint = self.DEFAULT_ENDPOINT
+ elif use_mtls_env == "always":
+ client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ elif use_mtls_env == "auto":
+ has_client_cert_source = (
+ client_options.client_cert_source is not None
+ or mtls.has_default_client_cert_source()
+ )
+ client_options.api_endpoint = (
+ self.DEFAULT_MTLS_ENDPOINT
+ if has_client_cert_source
+ else self.DEFAULT_ENDPOINT
+ )
+ else:
+ raise MutualTLSChannelError(
+ "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always"
+ )
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, ReservationServiceTransport):
# transport is a ReservationServiceTransport instance.
- if credentials:
+ if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
+ if client_options.scopes:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its scopes directly."
+ )
self._transport = transport
- elif client_options is None or (
- client_options.api_endpoint is None
- and client_options.client_cert_source is None
- ):
- # Don't trigger mTLS if we get an empty ClientOptions.
+ else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
- credentials=credentials, host=self.DEFAULT_ENDPOINT
- )
- else:
- # We have a non-empty ClientOptions. If client_cert_source is
- # provided, trigger mTLS with user provided endpoint or the default
- # mTLS endpoint.
- if client_options.client_cert_source:
- api_mtls_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_MTLS_ENDPOINT
- )
- else:
- api_mtls_endpoint = None
-
- api_endpoint = (
- client_options.api_endpoint
- if client_options.api_endpoint
- else self.DEFAULT_ENDPOINT
- )
-
- self._transport = ReservationServiceGrpcTransport(
credentials=credentials,
- host=api_endpoint,
- api_mtls_endpoint=api_mtls_endpoint,
+ credentials_file=client_options.credentials_file,
+ host=client_options.api_endpoint,
+ scopes=client_options.scopes,
+ api_mtls_endpoint=client_options.api_endpoint,
client_cert_source=client_options.client_cert_source,
+ quota_project_id=client_options.quota_project_id,
)
def create_reservation(
@@ -350,34 +365,42 @@ def create_reservation(
# 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, reservation, reservation_id]):
+ has_flattened_params = any([parent, reservation, reservation_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 = gcbr_reservation.CreateReservationRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a gcbr_reservation.CreateReservationRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, gcbr_reservation.CreateReservationRequest):
+ request = gcbr_reservation.CreateReservationRequest(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 reservation is not None:
- request.reservation = reservation
- if reservation_id is not None:
- request.reservation_id = reservation_id
+ if parent is not None:
+ request.parent = parent
+ if reservation is not None:
+ request.reservation = reservation
+ if reservation_id is not None:
+ request.reservation_id = reservation_id
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = gapic_v1.method.wrap_method(
- self._transport.create_reservation,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[self._transport.create_reservation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -399,9 +422,8 @@ def list_reservations(
The request object. The request for
[ReservationService.ListReservations][google.cloud.bigquery.reservation.v1.ReservationService.ListReservations].
parent (:class:`str`):
- Required. The parent resource name
- containing project and location, e.g.:
- "projects/myproject/locations/US".
+ Required. The parent resource name containing project
+ and location, e.g.: ``projects/myproject/locations/US``
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -424,27 +446,29 @@ def list_reservations(
# 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 = reservation.ListReservationsRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.ListReservationsRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.ListReservationsRequest):
+ request = reservation.ListReservationsRequest(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_reservations,
- default_timeout=None,
- client_info=_client_info,
- )
+ rpc = self._transport._wrapped_methods[self._transport.list_reservations]
# Certain fields should be provided within the metadata header;
# add these here.
@@ -453,12 +477,12 @@ def list_reservations(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListReservationsPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -502,27 +526,29 @@ def get_reservation(
# 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 = reservation.GetReservationRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.GetReservationRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.GetReservationRequest):
+ request = reservation.GetReservationRequest(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_reservation,
- default_timeout=None,
- client_info=_client_info,
- )
+ rpc = self._transport._wrapped_methods[self._transport.get_reservation]
# Certain fields should be provided within the metadata header;
# add these here.
@@ -531,7 +557,7 @@ def get_reservation(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -570,30 +596,40 @@ def delete_reservation(
# 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 = reservation.DeleteReservationRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.DeleteReservationRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.DeleteReservationRequest):
+ request = reservation.DeleteReservationRequest(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_reservation,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[self._transport.delete_reservation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
- rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
def update_reservation(
self,
@@ -638,32 +674,42 @@ def update_reservation(
# 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([reservation, update_mask]):
+ has_flattened_params = any([reservation, 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 = gcbr_reservation.UpdateReservationRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a gcbr_reservation.UpdateReservationRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, gcbr_reservation.UpdateReservationRequest):
+ request = gcbr_reservation.UpdateReservationRequest(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 reservation is not None:
- request.reservation = reservation
- if update_mask is not None:
- request.update_mask = update_mask
+ if reservation is not None:
+ request.reservation = reservation
+ 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_reservation,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[self._transport.update_reservation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("reservation.name", request.reservation.name),)
+ ),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -685,9 +731,8 @@ def create_capacity_commitment(
The request object. The request for
[ReservationService.CreateCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.CreateCapacityCommitment].
parent (:class:`str`):
- Required. Resource name of the parent
- reservation. E.g.,
- projects/myproject/locations/US
+ Required. Resource name of the parent reservation. E.g.,
+ ``projects/myproject/locations/US``
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -725,32 +770,42 @@ def create_capacity_commitment(
# 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, capacity_commitment]):
+ has_flattened_params = any([parent, capacity_commitment])
+ 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 = reservation.CreateCapacityCommitmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.CreateCapacityCommitmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.CreateCapacityCommitmentRequest):
+ request = reservation.CreateCapacityCommitmentRequest(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 capacity_commitment is not None:
- request.capacity_commitment = capacity_commitment
+ if parent is not None:
+ request.parent = parent
+ if capacity_commitment is not None:
+ request.capacity_commitment = capacity_commitment
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = gapic_v1.method.wrap_method(
- self._transport.create_capacity_commitment,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[
+ self._transport.create_capacity_commitment
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -772,9 +827,8 @@ def list_capacity_commitments(
The request object. The request for
[ReservationService.ListCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.ListCapacityCommitments].
parent (:class:`str`):
- Required. Resource name of the parent
- reservation. E.g.,
- projects/myproject/locations/US
+ Required. Resource name of the parent reservation. E.g.,
+ ``projects/myproject/locations/US``
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -797,27 +851,31 @@ def list_capacity_commitments(
# 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 = reservation.ListCapacityCommitmentsRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.ListCapacityCommitmentsRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.ListCapacityCommitmentsRequest):
+ request = reservation.ListCapacityCommitmentsRequest(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_capacity_commitments,
- default_timeout=None,
- client_info=_client_info,
- )
+ rpc = self._transport._wrapped_methods[
+ self._transport.list_capacity_commitments
+ ]
# Certain fields should be provided within the metadata header;
# add these here.
@@ -826,12 +884,12 @@ def list_capacity_commitments(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListCapacityCommitmentsPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -853,9 +911,9 @@ def get_capacity_commitment(
The request object. The request for
[ReservationService.GetCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.GetCapacityCommitment].
name (:class:`str`):
- Required. Resource name of the
- capacity commitment to retrieve. E.g.,
- projects/myproject/locations/US/capacityCommitments/123
+ Required. Resource name of the capacity commitment to
+ retrieve. E.g.,
+ ``projects/myproject/locations/US/capacityCommitments/123``
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -887,27 +945,29 @@ def get_capacity_commitment(
# 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 = reservation.GetCapacityCommitmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.GetCapacityCommitmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.GetCapacityCommitmentRequest):
+ request = reservation.GetCapacityCommitmentRequest(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_capacity_commitment,
- default_timeout=None,
- client_info=_client_info,
- )
+ rpc = self._transport._wrapped_methods[self._transport.get_capacity_commitment]
# Certain fields should be provided within the metadata header;
# add these here.
@@ -916,7 +976,7 @@ def get_capacity_commitment(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -939,9 +999,9 @@ def delete_capacity_commitment(
The request object. The request for
[ReservationService.DeleteCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.DeleteCapacityCommitment].
name (:class:`str`):
- Required. Resource name of the
- capacity commitment to delete. E.g.,
- projects/myproject/locations/US/capacityCommitments/123
+ Required. Resource name of the capacity commitment to
+ delete. E.g.,
+ ``projects/myproject/locations/US/capacityCommitments/123``
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -955,30 +1015,42 @@ def delete_capacity_commitment(
# 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 = reservation.DeleteCapacityCommitmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.DeleteCapacityCommitmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.DeleteCapacityCommitmentRequest):
+ request = reservation.DeleteCapacityCommitmentRequest(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_capacity_commitment,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[
+ self._transport.delete_capacity_commitment
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
- rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
def update_capacity_commitment(
self,
@@ -1043,32 +1115,44 @@ def update_capacity_commitment(
# 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([capacity_commitment, update_mask]):
+ has_flattened_params = any([capacity_commitment, 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 = reservation.UpdateCapacityCommitmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.UpdateCapacityCommitmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.UpdateCapacityCommitmentRequest):
+ request = reservation.UpdateCapacityCommitmentRequest(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 capacity_commitment is not None:
- request.capacity_commitment = capacity_commitment
- if update_mask is not None:
- request.update_mask = update_mask
+ if capacity_commitment is not None:
+ request.capacity_commitment = capacity_commitment
+ 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_capacity_commitment,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[
+ self._transport.update_capacity_commitment
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("capacity_commitment.name", request.capacity_commitment.name),)
+ ),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -1099,7 +1183,7 @@ def split_capacity_commitment(
[ReservationService.SplitCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.SplitCapacityCommitment].
name (:class:`str`):
Required. The resource name e.g.,:
- projects/myproject/locations/US/capacityCommitments/123
+ ``projects/myproject/locations/US/capacityCommitments/123``
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -1125,32 +1209,42 @@ def split_capacity_commitment(
# 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, slot_count]):
+ has_flattened_params = any([name, slot_count])
+ 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 = reservation.SplitCapacityCommitmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.SplitCapacityCommitmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.SplitCapacityCommitmentRequest):
+ request = reservation.SplitCapacityCommitmentRequest(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 slot_count is not None:
- request.slot_count = slot_count
+ if name is not None:
+ request.name = name
+ if slot_count is not None:
+ request.slot_count = slot_count
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = gapic_v1.method.wrap_method(
- self._transport.split_capacity_commitment,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[
+ self._transport.split_capacity_commitment
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -1181,9 +1275,8 @@ def merge_capacity_commitments(
The request object. The request for
[ReservationService.MergeCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.MergeCapacityCommitments].
parent (:class:`str`):
- Parent resource that identifies admin
- project and location e.g.,
- projects/myproject/locations/us
+ Parent resource that identifies admin project and
+ location e.g., ``projects/myproject/locations/us``
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -1192,6 +1285,9 @@ def merge_capacity_commitments(
These capacity commitments must exist
under admin project and location
specified in the parent.
+ ID is the last portion of capacity
+ commitment name e.g., 'abc' for
+ projects/myproject/locations/US/capacityCommitments/abc
This corresponds to the ``capacity_commitment_ids`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -1223,32 +1319,42 @@ def merge_capacity_commitments(
# 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, capacity_commitment_ids]):
+ has_flattened_params = any([parent, capacity_commitment_ids])
+ 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 = reservation.MergeCapacityCommitmentsRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.MergeCapacityCommitmentsRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.MergeCapacityCommitmentsRequest):
+ request = reservation.MergeCapacityCommitmentsRequest(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 capacity_commitment_ids is not None:
- request.capacity_commitment_ids = capacity_commitment_ids
+ if parent is not None:
+ request.parent = parent
+ if capacity_commitment_ids is not None:
+ request.capacity_commitment_ids = capacity_commitment_ids
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = gapic_v1.method.wrap_method(
- self._transport.merge_capacity_commitments,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[
+ self._transport.merge_capacity_commitments
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -1331,32 +1437,40 @@ def create_assignment(
# 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, assignment]):
+ has_flattened_params = any([parent, assignment])
+ 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 = reservation.CreateAssignmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.CreateAssignmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.CreateAssignmentRequest):
+ request = reservation.CreateAssignmentRequest(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 assignment is not None:
- request.assignment = assignment
+ if parent is not None:
+ request.parent = parent
+ if assignment is not None:
+ request.assignment = assignment
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = gapic_v1.method.wrap_method(
- self._transport.create_assignment,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[self._transport.create_assignment]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -1427,27 +1541,29 @@ def list_assignments(
# 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 = reservation.ListAssignmentsRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.ListAssignmentsRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.ListAssignmentsRequest):
+ request = reservation.ListAssignmentsRequest(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_assignments,
- default_timeout=None,
- client_info=_client_info,
- )
+ rpc = self._transport._wrapped_methods[self._transport.list_assignments]
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1456,12 +1572,12 @@ def list_assignments(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListAssignmentsPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -1515,30 +1631,40 @@ def delete_assignment(
# 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 = reservation.DeleteAssignmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.DeleteAssignmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.DeleteAssignmentRequest):
+ request = reservation.DeleteAssignmentRequest(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_assignment,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[self._transport.delete_assignment]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
- rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
def search_assignments(
self,
@@ -1583,10 +1709,9 @@ def search_assignments(
Note: "bigquery.reservationAssignments.search"
permission is required on the related assignee.
parent (:class:`str`):
- Required. The resource name of the
- admin project(containing project and
- location), e.g.:
- "projects/myproject/locations/US".
+ Required. The resource name of the admin
+ project(containing project and location), e.g.:
+ ``projects/myproject/locations/US``.
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -1621,29 +1746,31 @@ def search_assignments(
# 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, query]):
+ has_flattened_params = any([parent, query])
+ 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 = reservation.SearchAssignmentsRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.SearchAssignmentsRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.SearchAssignmentsRequest):
+ request = reservation.SearchAssignmentsRequest(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 query is not None:
- request.query = query
+ if parent is not None:
+ request.parent = parent
+ if query is not None:
+ request.query = query
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = gapic_v1.method.wrap_method(
- self._transport.search_assignments,
- default_timeout=None,
- client_info=_client_info,
- )
+ rpc = self._transport._wrapped_methods[self._transport.search_assignments]
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1652,12 +1779,12 @@ def search_assignments(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.SearchAssignmentsPager(
- method=rpc, request=request, response=response
+ method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
@@ -1718,32 +1845,40 @@ def move_assignment(
# 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, destination_id]):
+ has_flattened_params = any([name, destination_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 = reservation.MoveAssignmentRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.MoveAssignmentRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.MoveAssignmentRequest):
+ request = reservation.MoveAssignmentRequest(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 destination_id is not None:
- request.destination_id = destination_id
+ if name is not None:
+ request.name = name
+ if destination_id is not None:
+ request.destination_id = destination_id
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
- rpc = gapic_v1.method.wrap_method(
- self._transport.move_assignment,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[self._transport.move_assignment]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -1784,27 +1919,29 @@ def get_bi_reservation(
# 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 = reservation.GetBiReservationRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.GetBiReservationRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.GetBiReservationRequest):
+ request = reservation.GetBiReservationRequest(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_bi_reservation,
- default_timeout=None,
- client_info=_client_info,
- )
+ rpc = self._transport._wrapped_methods[self._transport.get_bi_reservation]
# Certain fields should be provided within the metadata header;
# add these here.
@@ -1813,7 +1950,7 @@ def get_bi_reservation(
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -1866,32 +2003,42 @@ def update_bi_reservation(
# 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([bi_reservation, update_mask]):
+ has_flattened_params = any([bi_reservation, 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 = reservation.UpdateBiReservationRequest(request)
+ # Minor optimization to avoid making a copy if the user passes
+ # in a reservation.UpdateBiReservationRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, reservation.UpdateBiReservationRequest):
+ request = reservation.UpdateBiReservationRequest(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 bi_reservation is not None:
- request.bi_reservation = bi_reservation
- if update_mask is not None:
- request.update_mask = update_mask
+ if bi_reservation is not None:
+ request.bi_reservation = bi_reservation
+ 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_bi_reservation,
- default_timeout=None,
- client_info=_client_info,
+ rpc = self._transport._wrapped_methods[self._transport.update_bi_reservation]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("bi_reservation.name", request.bi_reservation.name),)
+ ),
)
# Send the request.
- response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
@@ -1900,8 +2047,8 @@ def update_bi_reservation(
try:
_client_info = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
- "google-cloud-bigquery-reservation"
- ).version
+ "google-cloud-bigquery-reservation",
+ ).version,
)
except pkg_resources.DistributionNotFound:
_client_info = gapic_v1.client_info.ClientInfo()
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/pagers.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/pagers.py
index f737b3ca..a20d3438 100644
--- a/google/cloud/bigquery/reservation_v1/services/reservation_service/pagers.py
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/pagers.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-from typing import Any, Callable, Iterable
+from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
from google.cloud.bigquery.reservation_v1.types import reservation
@@ -40,11 +40,11 @@ class ListReservationsPager:
def __init__(
self,
- method: Callable[
- [reservation.ListReservationsRequest], reservation.ListReservationsResponse
- ],
+ method: Callable[..., reservation.ListReservationsResponse],
request: reservation.ListReservationsRequest,
response: reservation.ListReservationsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -55,10 +55,13 @@ def __init__(
The initial request object.
response (:class:`~.reservation.ListReservationsResponse`):
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 = reservation.ListReservationsRequest(request)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@@ -68,7 +71,7 @@ def pages(self) -> Iterable[reservation.ListReservationsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[reservation.Reservation]:
@@ -79,6 +82,72 @@ def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+class ListReservationsAsyncPager:
+ """A pager for iterating through ``list_reservations`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.reservation.ListReservationsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``reservations`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListReservations`` requests and continue to iterate
+ through the ``reservations`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.reservation.ListReservationsResponse`
+ 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[reservation.ListReservationsResponse]],
+ request: reservation.ListReservationsRequest,
+ response: reservation.ListReservationsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.reservation.ListReservationsRequest`):
+ The initial request object.
+ response (:class:`~.reservation.ListReservationsResponse`):
+ 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 = reservation.ListReservationsRequest(request)
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(self) -> AsyncIterable[reservation.ListReservationsResponse]:
+ 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[reservation.Reservation]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.reservations:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
class ListCapacityCommitmentsPager:
"""A pager for iterating through ``list_capacity_commitments`` requests.
@@ -99,12 +168,11 @@ class ListCapacityCommitmentsPager:
def __init__(
self,
- method: Callable[
- [reservation.ListCapacityCommitmentsRequest],
- reservation.ListCapacityCommitmentsResponse,
- ],
+ method: Callable[..., reservation.ListCapacityCommitmentsResponse],
request: reservation.ListCapacityCommitmentsRequest,
response: reservation.ListCapacityCommitmentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -115,10 +183,13 @@ def __init__(
The initial request object.
response (:class:`~.reservation.ListCapacityCommitmentsResponse`):
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 = reservation.ListCapacityCommitmentsRequest(request)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@@ -128,7 +199,7 @@ def pages(self) -> Iterable[reservation.ListCapacityCommitmentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[reservation.CapacityCommitment]:
@@ -139,6 +210,72 @@ def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+class ListCapacityCommitmentsAsyncPager:
+ """A pager for iterating through ``list_capacity_commitments`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.reservation.ListCapacityCommitmentsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``capacity_commitments`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListCapacityCommitments`` requests and continue to iterate
+ through the ``capacity_commitments`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.reservation.ListCapacityCommitmentsResponse`
+ 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[reservation.ListCapacityCommitmentsResponse]],
+ request: reservation.ListCapacityCommitmentsRequest,
+ response: reservation.ListCapacityCommitmentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.reservation.ListCapacityCommitmentsRequest`):
+ The initial request object.
+ response (:class:`~.reservation.ListCapacityCommitmentsResponse`):
+ 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 = reservation.ListCapacityCommitmentsRequest(request)
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(self) -> AsyncIterable[reservation.ListCapacityCommitmentsResponse]:
+ 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[reservation.CapacityCommitment]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.capacity_commitments:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
class ListAssignmentsPager:
"""A pager for iterating through ``list_assignments`` requests.
@@ -159,11 +296,11 @@ class ListAssignmentsPager:
def __init__(
self,
- method: Callable[
- [reservation.ListAssignmentsRequest], reservation.ListAssignmentsResponse
- ],
+ method: Callable[..., reservation.ListAssignmentsResponse],
request: reservation.ListAssignmentsRequest,
response: reservation.ListAssignmentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -174,10 +311,13 @@ def __init__(
The initial request object.
response (:class:`~.reservation.ListAssignmentsResponse`):
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 = reservation.ListAssignmentsRequest(request)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@@ -187,7 +327,7 @@ def pages(self) -> Iterable[reservation.ListAssignmentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[reservation.Assignment]:
@@ -198,6 +338,72 @@ def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+class ListAssignmentsAsyncPager:
+ """A pager for iterating through ``list_assignments`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.reservation.ListAssignmentsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``assignments`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListAssignments`` requests and continue to iterate
+ through the ``assignments`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.reservation.ListAssignmentsResponse`
+ 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[reservation.ListAssignmentsResponse]],
+ request: reservation.ListAssignmentsRequest,
+ response: reservation.ListAssignmentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.reservation.ListAssignmentsRequest`):
+ The initial request object.
+ response (:class:`~.reservation.ListAssignmentsResponse`):
+ 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 = reservation.ListAssignmentsRequest(request)
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(self) -> AsyncIterable[reservation.ListAssignmentsResponse]:
+ 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[reservation.Assignment]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.assignments:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
class SearchAssignmentsPager:
"""A pager for iterating through ``search_assignments`` requests.
@@ -218,12 +424,11 @@ class SearchAssignmentsPager:
def __init__(
self,
- method: Callable[
- [reservation.SearchAssignmentsRequest],
- reservation.SearchAssignmentsResponse,
- ],
+ method: Callable[..., reservation.SearchAssignmentsResponse],
request: reservation.SearchAssignmentsRequest,
response: reservation.SearchAssignmentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
@@ -234,10 +439,13 @@ def __init__(
The initial request object.
response (:class:`~.reservation.SearchAssignmentsResponse`):
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 = reservation.SearchAssignmentsRequest(request)
self._response = response
+ self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@@ -247,7 +455,7 @@ def pages(self) -> Iterable[reservation.SearchAssignmentsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
- self._response = self._method(self._request)
+ self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[reservation.Assignment]:
@@ -256,3 +464,69 @@ def __iter__(self) -> Iterable[reservation.Assignment]:
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class SearchAssignmentsAsyncPager:
+ """A pager for iterating through ``search_assignments`` requests.
+
+ This class thinly wraps an initial
+ :class:`~.reservation.SearchAssignmentsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``assignments`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``SearchAssignments`` requests and continue to iterate
+ through the ``assignments`` field on the
+ corresponding responses.
+
+ All the usual :class:`~.reservation.SearchAssignmentsResponse`
+ 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[reservation.SearchAssignmentsResponse]],
+ request: reservation.SearchAssignmentsRequest,
+ response: reservation.SearchAssignmentsResponse,
+ *,
+ metadata: Sequence[Tuple[str, str]] = ()
+ ):
+ """Instantiate the pager.
+
+ Args:
+ method (Callable): The method that was originally called, and
+ which instantiated this pager.
+ request (:class:`~.reservation.SearchAssignmentsRequest`):
+ The initial request object.
+ response (:class:`~.reservation.SearchAssignmentsResponse`):
+ 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 = reservation.SearchAssignmentsRequest(request)
+ self._response = response
+ self._metadata = metadata
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._response, name)
+
+ @property
+ async def pages(self) -> AsyncIterable[reservation.SearchAssignmentsResponse]:
+ 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[reservation.Assignment]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.assignments:
+ yield response
+
+ return async_generator()
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/__init__.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/__init__.py
index c558105d..5951881d 100644
--- a/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/__init__.py
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/__init__.py
@@ -20,6 +20,7 @@
from .base import ReservationServiceTransport
from .grpc import ReservationServiceGrpcTransport
+from .grpc_asyncio import ReservationServiceGrpcAsyncIOTransport
# Compile a registry of transports.
@@ -27,6 +28,11 @@
OrderedDict()
) # type: Dict[str, Type[ReservationServiceTransport]]
_transport_registry["grpc"] = ReservationServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = ReservationServiceGrpcAsyncIOTransport
-__all__ = ("ReservationServiceTransport", "ReservationServiceGrpcTransport")
+__all__ = (
+ "ReservationServiceTransport",
+ "ReservationServiceGrpcTransport",
+ "ReservationServiceGrpcAsyncIOTransport",
+)
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/base.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/base.py
index ec94d7bf..82e5fd6b 100644
--- a/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/base.py
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/base.py
@@ -17,8 +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.auth import credentials # type: ignore
from google.cloud.bigquery.reservation_v1.types import reservation
@@ -26,7 +30,17 @@
from google.protobuf import empty_pb2 as empty # type: ignore
-class ReservationServiceTransport(metaclass=abc.ABCMeta):
+try:
+ _client_info = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution(
+ "google-cloud-bigquery-reservation",
+ ).version,
+ )
+except pkg_resources.DistributionNotFound:
+ _client_info = gapic_v1.client_info.ClientInfo()
+
+
+class ReservationServiceTransport(abc.ABC):
"""Abstract transport class for ReservationService."""
AUTH_SCOPES = (
@@ -39,6 +53,10 @@ def __init__(
*,
host: str = "bigqueryreservation.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.
@@ -49,6 +67,12 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scope (Optional[Sequence[str]]): A list of scopes.
+ 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:
@@ -57,153 +81,312 @@ def __init__(
# If no credentials are provided, then determine the appropriate
# defaults.
- if credentials is None:
- credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
+ if credentials and credentials_file:
+ raise exceptions.DuplicateCredentialArgs(
+ "'credentials_file' and 'credentials' are mutually exclusive"
+ )
+
+ if credentials_file is not None:
+ credentials, _ = auth.load_credentials_from_file(
+ credentials_file, scopes=scopes, 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.create_reservation: gapic_v1.method.wrap_method(
+ self.create_reservation, default_timeout=None, client_info=_client_info,
+ ),
+ self.list_reservations: gapic_v1.method.wrap_method(
+ self.list_reservations, default_timeout=None, client_info=_client_info,
+ ),
+ self.get_reservation: gapic_v1.method.wrap_method(
+ self.get_reservation, default_timeout=None, client_info=_client_info,
+ ),
+ self.delete_reservation: gapic_v1.method.wrap_method(
+ self.delete_reservation, default_timeout=None, client_info=_client_info,
+ ),
+ self.update_reservation: gapic_v1.method.wrap_method(
+ self.update_reservation, default_timeout=None, client_info=_client_info,
+ ),
+ self.create_capacity_commitment: gapic_v1.method.wrap_method(
+ self.create_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ self.list_capacity_commitments: gapic_v1.method.wrap_method(
+ self.list_capacity_commitments,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ self.get_capacity_commitment: gapic_v1.method.wrap_method(
+ self.get_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ self.delete_capacity_commitment: gapic_v1.method.wrap_method(
+ self.delete_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ self.update_capacity_commitment: gapic_v1.method.wrap_method(
+ self.update_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ self.split_capacity_commitment: gapic_v1.method.wrap_method(
+ self.split_capacity_commitment,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ self.merge_capacity_commitments: gapic_v1.method.wrap_method(
+ self.merge_capacity_commitments,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ self.create_assignment: gapic_v1.method.wrap_method(
+ self.create_assignment, default_timeout=None, client_info=_client_info,
+ ),
+ self.list_assignments: gapic_v1.method.wrap_method(
+ self.list_assignments, default_timeout=None, client_info=_client_info,
+ ),
+ self.delete_assignment: gapic_v1.method.wrap_method(
+ self.delete_assignment, default_timeout=None, client_info=_client_info,
+ ),
+ self.search_assignments: gapic_v1.method.wrap_method(
+ self.search_assignments, default_timeout=None, client_info=_client_info,
+ ),
+ self.move_assignment: gapic_v1.method.wrap_method(
+ self.move_assignment, default_timeout=None, client_info=_client_info,
+ ),
+ self.get_bi_reservation: gapic_v1.method.wrap_method(
+ self.get_bi_reservation, default_timeout=None, client_info=_client_info,
+ ),
+ self.update_bi_reservation: gapic_v1.method.wrap_method(
+ self.update_bi_reservation,
+ default_timeout=None,
+ client_info=_client_info,
+ ),
+ }
+
@property
def create_reservation(
- self
+ self,
) -> typing.Callable[
- [gcbr_reservation.CreateReservationRequest], gcbr_reservation.Reservation
+ [gcbr_reservation.CreateReservationRequest],
+ typing.Union[
+ gcbr_reservation.Reservation, typing.Awaitable[gcbr_reservation.Reservation]
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def list_reservations(
- self
+ self,
) -> typing.Callable[
- [reservation.ListReservationsRequest], reservation.ListReservationsResponse
+ [reservation.ListReservationsRequest],
+ typing.Union[
+ reservation.ListReservationsResponse,
+ typing.Awaitable[reservation.ListReservationsResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def get_reservation(
- self
- ) -> typing.Callable[[reservation.GetReservationRequest], reservation.Reservation]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [reservation.GetReservationRequest],
+ typing.Union[
+ reservation.Reservation, typing.Awaitable[reservation.Reservation]
+ ],
+ ]:
+ raise NotImplementedError()
@property
def delete_reservation(
- self
- ) -> typing.Callable[[reservation.DeleteReservationRequest], empty.Empty]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [reservation.DeleteReservationRequest],
+ typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ ]:
+ raise NotImplementedError()
@property
def update_reservation(
- self
+ self,
) -> typing.Callable[
- [gcbr_reservation.UpdateReservationRequest], gcbr_reservation.Reservation
+ [gcbr_reservation.UpdateReservationRequest],
+ typing.Union[
+ gcbr_reservation.Reservation, typing.Awaitable[gcbr_reservation.Reservation]
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def create_capacity_commitment(
- self
+ self,
) -> typing.Callable[
- [reservation.CreateCapacityCommitmentRequest], reservation.CapacityCommitment
+ [reservation.CreateCapacityCommitmentRequest],
+ typing.Union[
+ reservation.CapacityCommitment,
+ typing.Awaitable[reservation.CapacityCommitment],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def list_capacity_commitments(
- self
+ self,
) -> typing.Callable[
[reservation.ListCapacityCommitmentsRequest],
- reservation.ListCapacityCommitmentsResponse,
+ typing.Union[
+ reservation.ListCapacityCommitmentsResponse,
+ typing.Awaitable[reservation.ListCapacityCommitmentsResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def get_capacity_commitment(
- self
+ self,
) -> typing.Callable[
- [reservation.GetCapacityCommitmentRequest], reservation.CapacityCommitment
+ [reservation.GetCapacityCommitmentRequest],
+ typing.Union[
+ reservation.CapacityCommitment,
+ typing.Awaitable[reservation.CapacityCommitment],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def delete_capacity_commitment(
- self
- ) -> typing.Callable[[reservation.DeleteCapacityCommitmentRequest], empty.Empty]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [reservation.DeleteCapacityCommitmentRequest],
+ typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ ]:
+ raise NotImplementedError()
@property
def update_capacity_commitment(
- self
+ self,
) -> typing.Callable[
- [reservation.UpdateCapacityCommitmentRequest], reservation.CapacityCommitment
+ [reservation.UpdateCapacityCommitmentRequest],
+ typing.Union[
+ reservation.CapacityCommitment,
+ typing.Awaitable[reservation.CapacityCommitment],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def split_capacity_commitment(
- self
+ self,
) -> typing.Callable[
[reservation.SplitCapacityCommitmentRequest],
- reservation.SplitCapacityCommitmentResponse,
+ typing.Union[
+ reservation.SplitCapacityCommitmentResponse,
+ typing.Awaitable[reservation.SplitCapacityCommitmentResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def merge_capacity_commitments(
- self
+ self,
) -> typing.Callable[
- [reservation.MergeCapacityCommitmentsRequest], reservation.CapacityCommitment
+ [reservation.MergeCapacityCommitmentsRequest],
+ typing.Union[
+ reservation.CapacityCommitment,
+ typing.Awaitable[reservation.CapacityCommitment],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def create_assignment(
- self
- ) -> typing.Callable[[reservation.CreateAssignmentRequest], reservation.Assignment]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [reservation.CreateAssignmentRequest],
+ typing.Union[reservation.Assignment, typing.Awaitable[reservation.Assignment]],
+ ]:
+ raise NotImplementedError()
@property
def list_assignments(
- self
+ self,
) -> typing.Callable[
- [reservation.ListAssignmentsRequest], reservation.ListAssignmentsResponse
+ [reservation.ListAssignmentsRequest],
+ typing.Union[
+ reservation.ListAssignmentsResponse,
+ typing.Awaitable[reservation.ListAssignmentsResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def delete_assignment(
- self
- ) -> typing.Callable[[reservation.DeleteAssignmentRequest], empty.Empty]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [reservation.DeleteAssignmentRequest],
+ typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ ]:
+ raise NotImplementedError()
@property
def search_assignments(
- self
+ self,
) -> typing.Callable[
- [reservation.SearchAssignmentsRequest], reservation.SearchAssignmentsResponse
+ [reservation.SearchAssignmentsRequest],
+ typing.Union[
+ reservation.SearchAssignmentsResponse,
+ typing.Awaitable[reservation.SearchAssignmentsResponse],
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def move_assignment(
- self
- ) -> typing.Callable[[reservation.MoveAssignmentRequest], reservation.Assignment]:
- raise NotImplementedError
+ self,
+ ) -> typing.Callable[
+ [reservation.MoveAssignmentRequest],
+ typing.Union[reservation.Assignment, typing.Awaitable[reservation.Assignment]],
+ ]:
+ raise NotImplementedError()
@property
def get_bi_reservation(
- self
+ self,
) -> typing.Callable[
- [reservation.GetBiReservationRequest], reservation.BiReservation
+ [reservation.GetBiReservationRequest],
+ typing.Union[
+ reservation.BiReservation, typing.Awaitable[reservation.BiReservation]
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
@property
def update_bi_reservation(
- self
+ self,
) -> typing.Callable[
- [reservation.UpdateBiReservationRequest], reservation.BiReservation
+ [reservation.UpdateBiReservationRequest],
+ typing.Union[
+ reservation.BiReservation, typing.Awaitable[reservation.BiReservation]
+ ],
]:
- raise NotImplementedError
+ raise NotImplementedError()
__all__ = ("ReservationServiceTransport",)
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/grpc.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/grpc.py
index 9e43af77..16987fe9 100644
--- a/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/grpc.py
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/grpc.py
@@ -15,9 +15,10 @@
# limitations under the License.
#
-from typing import Callable, Dict, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
+from google import auth # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
@@ -60,14 +61,19 @@ class ReservationServiceGrpcTransport(ReservationServiceTransport):
top of HTTP/2); the ``grpcio`` package must be installed.
"""
+ _stubs: Dict[str, Callable]
+
def __init__(
self,
*,
host: str = "bigqueryreservation.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
+ client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
+ quota_project_id: Optional[str] = None
) -> None:
"""Instantiate the transport.
@@ -79,6 +85,11 @@ def __init__(
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
+ ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
@@ -89,10 +100,14 @@ 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
+ 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
@@ -108,6 +123,11 @@ def __init__(
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:
@@ -119,22 +139,34 @@ def __init__(
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
- self._grpc_channel = grpc_helpers.create_channel(
+ self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
+ credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
- scopes=self.AUTH_SCOPES,
+ scopes=scopes or self.AUTH_SCOPES,
+ quota_project_id=quota_project_id,
)
- # Run the base constructor.
- super().__init__(host=host, credentials=credentials)
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 = "bigqueryreservation.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.
@@ -145,13 +177,31 @@ def create_channel(
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ 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, scopes=cls.AUTH_SCOPES, **kwargs
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ **kwargs
)
@property
@@ -165,7 +215,7 @@ def grpc_channel(self) -> grpc.Channel:
# have one.
if not hasattr(self, "_grpc_channel"):
self._grpc_channel = self.create_channel(
- self._host, credentials=self._credentials
+ self._host, credentials=self._credentials,
)
# Return the channel from cache.
@@ -173,7 +223,7 @@ def grpc_channel(self) -> grpc.Channel:
@property
def create_reservation(
- self
+ self,
) -> Callable[
[gcbr_reservation.CreateReservationRequest], gcbr_reservation.Reservation
]:
@@ -201,7 +251,7 @@ def create_reservation(
@property
def list_reservations(
- self
+ self,
) -> Callable[
[reservation.ListReservationsRequest], reservation.ListReservationsResponse
]:
@@ -230,7 +280,7 @@ def list_reservations(
@property
def get_reservation(
- self
+ self,
) -> Callable[[reservation.GetReservationRequest], reservation.Reservation]:
r"""Return a callable for the get reservation method over gRPC.
@@ -256,7 +306,7 @@ def get_reservation(
@property
def delete_reservation(
- self
+ self,
) -> Callable[[reservation.DeleteReservationRequest], empty.Empty]:
r"""Return a callable for the delete reservation method over gRPC.
@@ -284,7 +334,7 @@ def delete_reservation(
@property
def update_reservation(
- self
+ self,
) -> Callable[
[gcbr_reservation.UpdateReservationRequest], gcbr_reservation.Reservation
]:
@@ -312,7 +362,7 @@ def update_reservation(
@property
def create_capacity_commitment(
- self
+ self,
) -> Callable[
[reservation.CreateCapacityCommitmentRequest], reservation.CapacityCommitment
]:
@@ -340,7 +390,7 @@ def create_capacity_commitment(
@property
def list_capacity_commitments(
- self
+ self,
) -> Callable[
[reservation.ListCapacityCommitmentsRequest],
reservation.ListCapacityCommitmentsResponse,
@@ -370,7 +420,7 @@ def list_capacity_commitments(
@property
def get_capacity_commitment(
- self
+ self,
) -> Callable[
[reservation.GetCapacityCommitmentRequest], reservation.CapacityCommitment
]:
@@ -398,7 +448,7 @@ def get_capacity_commitment(
@property
def delete_capacity_commitment(
- self
+ self,
) -> Callable[[reservation.DeleteCapacityCommitmentRequest], empty.Empty]:
r"""Return a callable for the delete capacity commitment method over gRPC.
@@ -426,7 +476,7 @@ def delete_capacity_commitment(
@property
def update_capacity_commitment(
- self
+ self,
) -> Callable[
[reservation.UpdateCapacityCommitmentRequest], reservation.CapacityCommitment
]:
@@ -461,7 +511,7 @@ def update_capacity_commitment(
@property
def split_capacity_commitment(
- self
+ self,
) -> Callable[
[reservation.SplitCapacityCommitmentRequest],
reservation.SplitCapacityCommitmentResponse,
@@ -498,7 +548,7 @@ def split_capacity_commitment(
@property
def merge_capacity_commitments(
- self
+ self,
) -> Callable[
[reservation.MergeCapacityCommitmentsRequest], reservation.CapacityCommitment
]:
@@ -535,7 +585,7 @@ def merge_capacity_commitments(
@property
def create_assignment(
- self
+ self,
) -> Callable[[reservation.CreateAssignmentRequest], reservation.Assignment]:
r"""Return a callable for the create assignment method over gRPC.
@@ -592,7 +642,7 @@ def create_assignment(
@property
def list_assignments(
- self
+ self,
) -> Callable[
[reservation.ListAssignmentsRequest], reservation.ListAssignmentsResponse
]:
@@ -641,7 +691,7 @@ def list_assignments(
@property
def delete_assignment(
- self
+ self,
) -> Callable[[reservation.DeleteAssignmentRequest], empty.Empty]:
r"""Return a callable for the delete assignment method over gRPC.
@@ -682,7 +732,7 @@ def delete_assignment(
@property
def search_assignments(
- self
+ self,
) -> Callable[
[reservation.SearchAssignmentsRequest], reservation.SearchAssignmentsResponse
]:
@@ -734,7 +784,7 @@ def search_assignments(
@property
def move_assignment(
- self
+ self,
) -> Callable[[reservation.MoveAssignmentRequest], reservation.Assignment]:
r"""Return a callable for the move assignment method over gRPC.
@@ -764,7 +814,7 @@ def move_assignment(
@property
def get_bi_reservation(
- self
+ self,
) -> Callable[[reservation.GetBiReservationRequest], reservation.BiReservation]:
r"""Return a callable for the get bi reservation method over gRPC.
@@ -790,7 +840,7 @@ def get_bi_reservation(
@property
def update_bi_reservation(
- self
+ self,
) -> Callable[[reservation.UpdateBiReservationRequest], reservation.BiReservation]:
r"""Return a callable for the update bi reservation method over gRPC.
diff --git a/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/grpc_asyncio.py b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/grpc_asyncio.py
new file mode 100644
index 00000000..36cfa61f
--- /dev/null
+++ b/google/cloud/bigquery/reservation_v1/services/reservation_service/transports/grpc_asyncio.py
@@ -0,0 +1,889 @@
+# -*- 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.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.bigquery.reservation_v1.types import reservation
+from google.cloud.bigquery.reservation_v1.types import reservation as gcbr_reservation
+from google.protobuf import empty_pb2 as empty # type: ignore
+
+from .base import ReservationServiceTransport
+from .grpc import ReservationServiceGrpcTransport
+
+
+class ReservationServiceGrpcAsyncIOTransport(ReservationServiceTransport):
+ """gRPC AsyncIO backend transport for ReservationService.
+
+ This API allows users to manage their flat-rate BigQuery
+ reservations.
+
+ A reservation provides computational resource guarantees, in the
+ form of `slots `__, to
+ users. A slot is a unit of computational power in BigQuery, and
+ serves as the basic unit of parallelism. In a scan of a
+ multi-partitioned table, a single slot operates on a single
+ partition of the table. A reservation resource exists as a child
+ resource of the admin project and location, e.g.:
+ ``projects/myproject/locations/US/reservations/reservationName``.
+
+ A capacity commitment is a way to purchase compute capacity for
+ BigQuery jobs (in the form of slots) with some committed period of
+ usage. A capacity commitment resource exists as a child resource of
+ the admin project and location, e.g.:
+ ``projects/myproject/locations/US/capacityCommitments/id``.
+
+ 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 = "bigqueryreservation.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 = "bigqueryreservation.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 create_reservation(
+ self,
+ ) -> Callable[
+ [gcbr_reservation.CreateReservationRequest],
+ Awaitable[gcbr_reservation.Reservation],
+ ]:
+ r"""Return a callable for the create reservation method over gRPC.
+
+ Creates a new reservation resource.
+
+ Returns:
+ Callable[[~.CreateReservationRequest],
+ Awaitable[~.Reservation]]:
+ 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_reservation" not in self._stubs:
+ self._stubs["create_reservation"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/CreateReservation",
+ request_serializer=gcbr_reservation.CreateReservationRequest.serialize,
+ response_deserializer=gcbr_reservation.Reservation.deserialize,
+ )
+ return self._stubs["create_reservation"]
+
+ @property
+ def list_reservations(
+ self,
+ ) -> Callable[
+ [reservation.ListReservationsRequest],
+ Awaitable[reservation.ListReservationsResponse],
+ ]:
+ r"""Return a callable for the list reservations method over gRPC.
+
+ Lists all the reservations for the project in the
+ specified location.
+
+ Returns:
+ Callable[[~.ListReservationsRequest],
+ Awaitable[~.ListReservationsResponse]]:
+ 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_reservations" not in self._stubs:
+ self._stubs["list_reservations"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/ListReservations",
+ request_serializer=reservation.ListReservationsRequest.serialize,
+ response_deserializer=reservation.ListReservationsResponse.deserialize,
+ )
+ return self._stubs["list_reservations"]
+
+ @property
+ def get_reservation(
+ self,
+ ) -> Callable[
+ [reservation.GetReservationRequest], Awaitable[reservation.Reservation]
+ ]:
+ r"""Return a callable for the get reservation method over gRPC.
+
+ Returns information about the reservation.
+
+ Returns:
+ Callable[[~.GetReservationRequest],
+ Awaitable[~.Reservation]]:
+ 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_reservation" not in self._stubs:
+ self._stubs["get_reservation"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/GetReservation",
+ request_serializer=reservation.GetReservationRequest.serialize,
+ response_deserializer=reservation.Reservation.deserialize,
+ )
+ return self._stubs["get_reservation"]
+
+ @property
+ def delete_reservation(
+ self,
+ ) -> Callable[[reservation.DeleteReservationRequest], Awaitable[empty.Empty]]:
+ r"""Return a callable for the delete reservation method over gRPC.
+
+ Deletes a reservation. Returns
+ ``google.rpc.Code.FAILED_PRECONDITION`` when reservation has
+ assignments.
+
+ Returns:
+ Callable[[~.DeleteReservationRequest],
+ Awaitable[~.Empty]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_reservation" not in self._stubs:
+ self._stubs["delete_reservation"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/DeleteReservation",
+ request_serializer=reservation.DeleteReservationRequest.serialize,
+ response_deserializer=empty.Empty.FromString,
+ )
+ return self._stubs["delete_reservation"]
+
+ @property
+ def update_reservation(
+ self,
+ ) -> Callable[
+ [gcbr_reservation.UpdateReservationRequest],
+ Awaitable[gcbr_reservation.Reservation],
+ ]:
+ r"""Return a callable for the update reservation method over gRPC.
+
+ Updates an existing reservation resource.
+
+ Returns:
+ Callable[[~.UpdateReservationRequest],
+ Awaitable[~.Reservation]]:
+ 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_reservation" not in self._stubs:
+ self._stubs["update_reservation"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/UpdateReservation",
+ request_serializer=gcbr_reservation.UpdateReservationRequest.serialize,
+ response_deserializer=gcbr_reservation.Reservation.deserialize,
+ )
+ return self._stubs["update_reservation"]
+
+ @property
+ def create_capacity_commitment(
+ self,
+ ) -> Callable[
+ [reservation.CreateCapacityCommitmentRequest],
+ Awaitable[reservation.CapacityCommitment],
+ ]:
+ r"""Return a callable for the create capacity commitment method over gRPC.
+
+ Creates a new capacity commitment resource.
+
+ Returns:
+ Callable[[~.CreateCapacityCommitmentRequest],
+ Awaitable[~.CapacityCommitment]]:
+ 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_capacity_commitment" not in self._stubs:
+ self._stubs["create_capacity_commitment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/CreateCapacityCommitment",
+ request_serializer=reservation.CreateCapacityCommitmentRequest.serialize,
+ response_deserializer=reservation.CapacityCommitment.deserialize,
+ )
+ return self._stubs["create_capacity_commitment"]
+
+ @property
+ def list_capacity_commitments(
+ self,
+ ) -> Callable[
+ [reservation.ListCapacityCommitmentsRequest],
+ Awaitable[reservation.ListCapacityCommitmentsResponse],
+ ]:
+ r"""Return a callable for the list capacity commitments method over gRPC.
+
+ Lists all the capacity commitments for the admin
+ project.
+
+ Returns:
+ Callable[[~.ListCapacityCommitmentsRequest],
+ Awaitable[~.ListCapacityCommitmentsResponse]]:
+ 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_capacity_commitments" not in self._stubs:
+ self._stubs["list_capacity_commitments"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/ListCapacityCommitments",
+ request_serializer=reservation.ListCapacityCommitmentsRequest.serialize,
+ response_deserializer=reservation.ListCapacityCommitmentsResponse.deserialize,
+ )
+ return self._stubs["list_capacity_commitments"]
+
+ @property
+ def get_capacity_commitment(
+ self,
+ ) -> Callable[
+ [reservation.GetCapacityCommitmentRequest],
+ Awaitable[reservation.CapacityCommitment],
+ ]:
+ r"""Return a callable for the get capacity commitment method over gRPC.
+
+ Returns information about the capacity commitment.
+
+ Returns:
+ Callable[[~.GetCapacityCommitmentRequest],
+ Awaitable[~.CapacityCommitment]]:
+ 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_capacity_commitment" not in self._stubs:
+ self._stubs["get_capacity_commitment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/GetCapacityCommitment",
+ request_serializer=reservation.GetCapacityCommitmentRequest.serialize,
+ response_deserializer=reservation.CapacityCommitment.deserialize,
+ )
+ return self._stubs["get_capacity_commitment"]
+
+ @property
+ def delete_capacity_commitment(
+ self,
+ ) -> Callable[
+ [reservation.DeleteCapacityCommitmentRequest], Awaitable[empty.Empty]
+ ]:
+ r"""Return a callable for the delete capacity commitment method over gRPC.
+
+ Deletes a capacity commitment. Attempting to delete capacity
+ commitment before its commitment_end_time will fail with the
+ error code ``google.rpc.Code.FAILED_PRECONDITION``.
+
+ Returns:
+ Callable[[~.DeleteCapacityCommitmentRequest],
+ Awaitable[~.Empty]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_capacity_commitment" not in self._stubs:
+ self._stubs["delete_capacity_commitment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/DeleteCapacityCommitment",
+ request_serializer=reservation.DeleteCapacityCommitmentRequest.serialize,
+ response_deserializer=empty.Empty.FromString,
+ )
+ return self._stubs["delete_capacity_commitment"]
+
+ @property
+ def update_capacity_commitment(
+ self,
+ ) -> Callable[
+ [reservation.UpdateCapacityCommitmentRequest],
+ Awaitable[reservation.CapacityCommitment],
+ ]:
+ r"""Return a callable for the update capacity commitment method over gRPC.
+
+ Updates an existing capacity commitment.
+
+ Only ``plan`` and ``renewal_plan`` fields can be updated.
+
+ Plan can only be changed to a plan of a longer commitment
+ period. Attempting to change to a plan with shorter commitment
+ period will fail with the error code
+ ``google.rpc.Code.FAILED_PRECONDITION``.
+
+ Returns:
+ Callable[[~.UpdateCapacityCommitmentRequest],
+ Awaitable[~.CapacityCommitment]]:
+ 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_capacity_commitment" not in self._stubs:
+ self._stubs["update_capacity_commitment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/UpdateCapacityCommitment",
+ request_serializer=reservation.UpdateCapacityCommitmentRequest.serialize,
+ response_deserializer=reservation.CapacityCommitment.deserialize,
+ )
+ return self._stubs["update_capacity_commitment"]
+
+ @property
+ def split_capacity_commitment(
+ self,
+ ) -> Callable[
+ [reservation.SplitCapacityCommitmentRequest],
+ Awaitable[reservation.SplitCapacityCommitmentResponse],
+ ]:
+ r"""Return a callable for the split capacity commitment method over gRPC.
+
+ Splits capacity commitment to two commitments of the same plan
+ and ``commitment_end_time``.
+
+ A common use case is to enable downgrading commitments.
+
+ For example, in order to downgrade from 10000 slots to 8000, you
+ might split a 10000 capacity commitment into commitments of 2000
+ and 8000. Then, you would change the plan of the first one to
+ ``FLEX`` and then delete it.
+
+ Returns:
+ Callable[[~.SplitCapacityCommitmentRequest],
+ Awaitable[~.SplitCapacityCommitmentResponse]]:
+ 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 "split_capacity_commitment" not in self._stubs:
+ self._stubs["split_capacity_commitment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/SplitCapacityCommitment",
+ request_serializer=reservation.SplitCapacityCommitmentRequest.serialize,
+ response_deserializer=reservation.SplitCapacityCommitmentResponse.deserialize,
+ )
+ return self._stubs["split_capacity_commitment"]
+
+ @property
+ def merge_capacity_commitments(
+ self,
+ ) -> Callable[
+ [reservation.MergeCapacityCommitmentsRequest],
+ Awaitable[reservation.CapacityCommitment],
+ ]:
+ r"""Return a callable for the merge capacity commitments method over gRPC.
+
+ Merges capacity commitments of the same plan into a single
+ commitment.
+
+ The resulting capacity commitment has the greater
+ commitment_end_time out of the to-be-merged capacity
+ commitments.
+
+ Attempting to merge capacity commitments of different plan will
+ fail with the error code
+ ``google.rpc.Code.FAILED_PRECONDITION``.
+
+ Returns:
+ Callable[[~.MergeCapacityCommitmentsRequest],
+ Awaitable[~.CapacityCommitment]]:
+ 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 "merge_capacity_commitments" not in self._stubs:
+ self._stubs["merge_capacity_commitments"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/MergeCapacityCommitments",
+ request_serializer=reservation.MergeCapacityCommitmentsRequest.serialize,
+ response_deserializer=reservation.CapacityCommitment.deserialize,
+ )
+ return self._stubs["merge_capacity_commitments"]
+
+ @property
+ def create_assignment(
+ self,
+ ) -> Callable[
+ [reservation.CreateAssignmentRequest], Awaitable[reservation.Assignment]
+ ]:
+ r"""Return a callable for the create assignment method over gRPC.
+
+ Creates an assignment object which allows the given project to
+ submit jobs of a certain type using slots from the specified
+ reservation.
+
+ Currently a resource (project, folder, organization) can only
+ have one assignment per each (job_type, location) combination,
+ and that reservation will be used for all jobs of the matching
+ type.
+
+ Different assignments can be created on different levels of the
+ projects, folders or organization hierarchy. During query
+ execution, the assignment is looked up at the project, folder
+ and organization levels in that order. The first assignment
+ found is applied to the query.
+
+ When creating assignments, it does not matter if other
+ assignments exist at higher levels.
+
+ Example:
+
+ - The organization ``organizationA`` contains two projects,
+ ``project1`` and ``project2``.
+ - Assignments for all three entities (``organizationA``,
+ ``project1``, and ``project2``) could all be created and
+ mapped to the same or different reservations.
+
+ Returns ``google.rpc.Code.PERMISSION_DENIED`` if user does not
+ have 'bigquery.admin' permissions on the project using the
+ reservation and the project that owns this reservation.
+
+ Returns ``google.rpc.Code.INVALID_ARGUMENT`` when location of
+ the assignment does not match location of the reservation.
+
+ Returns:
+ Callable[[~.CreateAssignmentRequest],
+ Awaitable[~.Assignment]]:
+ 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_assignment" not in self._stubs:
+ self._stubs["create_assignment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/CreateAssignment",
+ request_serializer=reservation.CreateAssignmentRequest.serialize,
+ response_deserializer=reservation.Assignment.deserialize,
+ )
+ return self._stubs["create_assignment"]
+
+ @property
+ def list_assignments(
+ self,
+ ) -> Callable[
+ [reservation.ListAssignmentsRequest],
+ Awaitable[reservation.ListAssignmentsResponse],
+ ]:
+ r"""Return a callable for the list assignments method over gRPC.
+
+ Lists assignments.
+
+ Only explicitly created assignments will be returned.
+
+ Example:
+
+ - Organization ``organizationA`` contains two projects,
+ ``project1`` and ``project2``.
+ - Reservation ``res1`` exists and was created previously.
+ - CreateAssignment was used previously to define the following
+ associations between entities and reservations:
+ ```` and ````
+
+ In this example, ListAssignments will just return the above two
+ assignments for reservation ``res1``, and no expansion/merge
+ will happen.
+
+ The wildcard "-" can be used for reservations in the request. In
+ that case all assignments belongs to the specified project and
+ location will be listed.
+
+ **Note** "-" cannot be used for projects nor locations.
+
+ Returns:
+ Callable[[~.ListAssignmentsRequest],
+ Awaitable[~.ListAssignmentsResponse]]:
+ 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_assignments" not in self._stubs:
+ self._stubs["list_assignments"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/ListAssignments",
+ request_serializer=reservation.ListAssignmentsRequest.serialize,
+ response_deserializer=reservation.ListAssignmentsResponse.deserialize,
+ )
+ return self._stubs["list_assignments"]
+
+ @property
+ def delete_assignment(
+ self,
+ ) -> Callable[[reservation.DeleteAssignmentRequest], Awaitable[empty.Empty]]:
+ r"""Return a callable for the delete assignment method over gRPC.
+
+ Deletes a assignment. No expansion will happen.
+
+ Example:
+
+ - Organization ``organizationA`` contains two projects,
+ ``project1`` and ``project2``.
+ - Reservation ``res1`` exists and was created previously.
+ - CreateAssignment was used previously to define the following
+ associations between entities and reservations:
+ ```` and ````
+
+ In this example, deletion of the ````
+ assignment won't affect the other assignment
+ ````. After said deletion, queries from
+ ``project1`` will still use ``res1`` while queries from
+ ``project2`` will switch to use on-demand mode.
+
+ Returns:
+ Callable[[~.DeleteAssignmentRequest],
+ Awaitable[~.Empty]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_assignment" not in self._stubs:
+ self._stubs["delete_assignment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/DeleteAssignment",
+ request_serializer=reservation.DeleteAssignmentRequest.serialize,
+ response_deserializer=empty.Empty.FromString,
+ )
+ return self._stubs["delete_assignment"]
+
+ @property
+ def search_assignments(
+ self,
+ ) -> Callable[
+ [reservation.SearchAssignmentsRequest],
+ Awaitable[reservation.SearchAssignmentsResponse],
+ ]:
+ r"""Return a callable for the search assignments method over gRPC.
+
+ Looks up assignments for a specified resource for a particular
+ region. If the request is about a project:
+
+ 1. Assignments created on the project will be returned if they
+ exist.
+ 2. Otherwise assignments created on the closest ancestor will be
+ returned.
+ 3. Assignments for different JobTypes will all be returned.
+
+ The same logic applies if the request is about a folder.
+
+ If the request is about an organization, then assignments
+ created on the organization will be returned (organization
+ doesn't have ancestors).
+
+ Comparing to ListAssignments, there are some behavior
+ differences:
+
+ 1. permission on the assignee will be verified in this API.
+ 2. Hierarchy lookup (project->folder->organization) happens in
+ this API.
+ 3. Parent here is ``projects/*/locations/*``, instead of
+ ``projects/*/locations/*reservations/*``.
+
+ **Note** "-" cannot be used for projects nor locations.
+
+ Returns:
+ Callable[[~.SearchAssignmentsRequest],
+ Awaitable[~.SearchAssignmentsResponse]]:
+ 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 "search_assignments" not in self._stubs:
+ self._stubs["search_assignments"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/SearchAssignments",
+ request_serializer=reservation.SearchAssignmentsRequest.serialize,
+ response_deserializer=reservation.SearchAssignmentsResponse.deserialize,
+ )
+ return self._stubs["search_assignments"]
+
+ @property
+ def move_assignment(
+ self,
+ ) -> Callable[
+ [reservation.MoveAssignmentRequest], Awaitable[reservation.Assignment]
+ ]:
+ r"""Return a callable for the move assignment method over gRPC.
+
+ Moves an assignment under a new reservation.
+ This differs from removing an existing assignment and
+ recreating a new one by providing a transactional change
+ that ensures an assignee always has an associated
+ reservation.
+
+ Returns:
+ Callable[[~.MoveAssignmentRequest],
+ Awaitable[~.Assignment]]:
+ 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 "move_assignment" not in self._stubs:
+ self._stubs["move_assignment"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/MoveAssignment",
+ request_serializer=reservation.MoveAssignmentRequest.serialize,
+ response_deserializer=reservation.Assignment.deserialize,
+ )
+ return self._stubs["move_assignment"]
+
+ @property
+ def get_bi_reservation(
+ self,
+ ) -> Callable[
+ [reservation.GetBiReservationRequest], Awaitable[reservation.BiReservation]
+ ]:
+ r"""Return a callable for the get bi reservation method over gRPC.
+
+ Retrieves a BI reservation.
+
+ Returns:
+ Callable[[~.GetBiReservationRequest],
+ Awaitable[~.BiReservation]]:
+ 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_bi_reservation" not in self._stubs:
+ self._stubs["get_bi_reservation"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/GetBiReservation",
+ request_serializer=reservation.GetBiReservationRequest.serialize,
+ response_deserializer=reservation.BiReservation.deserialize,
+ )
+ return self._stubs["get_bi_reservation"]
+
+ @property
+ def update_bi_reservation(
+ self,
+ ) -> Callable[
+ [reservation.UpdateBiReservationRequest], Awaitable[reservation.BiReservation]
+ ]:
+ r"""Return a callable for the update bi reservation method over gRPC.
+
+ Updates a BI reservation.
+
+ Only fields specified in the ``field_mask`` are updated.
+
+ A singleton BI reservation always exists with default size 0. In
+ order to reserve BI capacity it needs to be updated to an amount
+ greater than 0. In order to release BI capacity reservation size
+ must be set to 0.
+
+ Returns:
+ Callable[[~.UpdateBiReservationRequest],
+ Awaitable[~.BiReservation]]:
+ 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_bi_reservation" not in self._stubs:
+ self._stubs["update_bi_reservation"] = self.grpc_channel.unary_unary(
+ "/google.cloud.bigquery.reservation.v1.ReservationService/UpdateBiReservation",
+ request_serializer=reservation.UpdateBiReservationRequest.serialize,
+ response_deserializer=reservation.BiReservation.deserialize,
+ )
+ return self._stubs["update_bi_reservation"]
+
+
+__all__ = ("ReservationServiceGrpcAsyncIOTransport",)
diff --git a/google/cloud/bigquery/reservation_v1/types/reservation.py b/google/cloud/bigquery/reservation_v1/types/reservation.py
index 603540c6..5a7fbdbe 100644
--- a/google/cloud/bigquery/reservation_v1/types/reservation.py
+++ b/google/cloud/bigquery/reservation_v1/types/reservation.py
@@ -88,7 +88,9 @@ class Reservation(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
+
slot_capacity = proto.Field(proto.INT64, number=2)
+
ignore_idle_slots = proto.Field(proto.BOOL, number=4)
@@ -150,14 +152,20 @@ class State(proto.Enum):
FAILED = 3
name = proto.Field(proto.STRING, number=1)
+
slot_count = proto.Field(proto.INT64, number=2)
- plan = proto.Field(proto.ENUM, number=3, enum=CommitmentPlan)
- state = proto.Field(proto.ENUM, number=4, enum=State)
+
+ plan = proto.Field(proto.ENUM, number=3, enum=CommitmentPlan,)
+
+ state = proto.Field(proto.ENUM, number=4, enum=State,)
+
commitment_end_time = proto.Field(
- proto.MESSAGE, number=5, message=timestamp.Timestamp
+ proto.MESSAGE, number=5, message=timestamp.Timestamp,
)
- failure_status = proto.Field(proto.MESSAGE, number=7, message=status.Status)
- renewal_plan = proto.Field(proto.ENUM, number=8, enum=CommitmentPlan)
+
+ failure_status = proto.Field(proto.MESSAGE, number=7, message=status.Status,)
+
+ renewal_plan = proto.Field(proto.ENUM, number=8, enum=CommitmentPlan,)
class CreateReservationRequest(proto.Message):
@@ -177,8 +185,10 @@ class CreateReservationRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
reservation_id = proto.Field(proto.STRING, number=2)
- reservation = proto.Field(proto.MESSAGE, number=3, message=Reservation)
+
+ reservation = proto.Field(proto.MESSAGE, number=3, message=Reservation,)
class ListReservationsRequest(proto.Message):
@@ -187,9 +197,8 @@ class ListReservationsRequest(proto.Message):
Attributes:
parent (str):
- Required. The parent resource name containing
- project and location, e.g.:
- "projects/myproject/locations/US".
+ Required. The parent resource name containing project and
+ location, e.g.: ``projects/myproject/locations/US``
page_size (int):
The maximum number of items to return per
page.
@@ -199,7 +208,9 @@ class ListReservationsRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
page_size = proto.Field(proto.INT32, number=2)
+
page_token = proto.Field(proto.STRING, number=3)
@@ -220,7 +231,8 @@ class ListReservationsResponse(proto.Message):
def raw_page(self):
return self
- reservations = proto.RepeatedField(proto.MESSAGE, number=1, message=Reservation)
+ reservations = proto.RepeatedField(proto.MESSAGE, number=1, message=Reservation,)
+
next_page_token = proto.Field(proto.STRING, number=2)
@@ -264,8 +276,9 @@ class UpdateReservationRequest(proto.Message):
be updated.
"""
- reservation = proto.Field(proto.MESSAGE, number=1, message=Reservation)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
+ reservation = proto.Field(proto.MESSAGE, number=1, message=Reservation,)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
class CreateCapacityCommitmentRequest(proto.Message):
@@ -274,9 +287,8 @@ class CreateCapacityCommitmentRequest(proto.Message):
Attributes:
parent (str):
- Required. Resource name of the parent
- reservation. E.g.,
- projects/myproject/locations/US
+ Required. Resource name of the parent reservation. E.g.,
+ ``projects/myproject/locations/US``
capacity_commitment (~.gcbr_reservation.CapacityCommitment):
Content of the capacity commitment to create.
enforce_single_admin_project_per_org (bool):
@@ -285,9 +297,11 @@ class CreateCapacityCommitmentRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
capacity_commitment = proto.Field(
- proto.MESSAGE, number=2, message=CapacityCommitment
+ proto.MESSAGE, number=2, message=CapacityCommitment,
)
+
enforce_single_admin_project_per_org = proto.Field(proto.BOOL, number=4)
@@ -297,9 +311,8 @@ class ListCapacityCommitmentsRequest(proto.Message):
Attributes:
parent (str):
- Required. Resource name of the parent
- reservation. E.g.,
- projects/myproject/locations/US
+ Required. Resource name of the parent reservation. E.g.,
+ ``projects/myproject/locations/US``
page_size (int):
The maximum number of items to return.
page_token (str):
@@ -308,7 +321,9 @@ class ListCapacityCommitmentsRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
page_size = proto.Field(proto.INT32, number=2)
+
page_token = proto.Field(proto.STRING, number=3)
@@ -331,8 +346,9 @@ def raw_page(self):
return self
capacity_commitments = proto.RepeatedField(
- proto.MESSAGE, number=1, message=CapacityCommitment
+ proto.MESSAGE, number=1, message=CapacityCommitment,
)
+
next_page_token = proto.Field(proto.STRING, number=2)
@@ -342,9 +358,9 @@ class GetCapacityCommitmentRequest(proto.Message):
Attributes:
name (str):
- Required. Resource name of the capacity
- commitment to retrieve. E.g.,
- projects/myproject/locations/US/capacityCommitments/123
+ Required. Resource name of the capacity commitment to
+ retrieve. E.g.,
+ ``projects/myproject/locations/US/capacityCommitments/123``
"""
name = proto.Field(proto.STRING, number=1)
@@ -356,9 +372,9 @@ class DeleteCapacityCommitmentRequest(proto.Message):
Attributes:
name (str):
- Required. Resource name of the capacity
- commitment to delete. E.g.,
- projects/myproject/locations/US/capacityCommitments/123
+ Required. Resource name of the capacity commitment to
+ delete. E.g.,
+ ``projects/myproject/locations/US/capacityCommitments/123``
"""
name = proto.Field(proto.STRING, number=1)
@@ -377,9 +393,10 @@ class UpdateCapacityCommitmentRequest(proto.Message):
"""
capacity_commitment = proto.Field(
- proto.MESSAGE, number=1, message=CapacityCommitment
+ proto.MESSAGE, number=1, message=CapacityCommitment,
)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
class SplitCapacityCommitmentRequest(proto.Message):
@@ -389,13 +406,14 @@ class SplitCapacityCommitmentRequest(proto.Message):
Attributes:
name (str):
Required. The resource name e.g.,:
- projects/myproject/locations/US/capacityCommitments/123
+ ``projects/myproject/locations/US/capacityCommitments/123``
slot_count (int):
Number of slots in the capacity commitment
after the split.
"""
name = proto.Field(proto.STRING, number=1)
+
slot_count = proto.Field(proto.INT64, number=2)
@@ -411,8 +429,9 @@ class SplitCapacityCommitmentResponse(proto.Message):
split.
"""
- first = proto.Field(proto.MESSAGE, number=1, message=CapacityCommitment)
- second = proto.Field(proto.MESSAGE, number=2, message=CapacityCommitment)
+ first = proto.Field(proto.MESSAGE, number=1, message=CapacityCommitment,)
+
+ second = proto.Field(proto.MESSAGE, number=2, message=CapacityCommitment,)
class MergeCapacityCommitmentsRequest(proto.Message):
@@ -421,17 +440,20 @@ class MergeCapacityCommitmentsRequest(proto.Message):
Attributes:
parent (str):
- Parent resource that identifies admin project
- and location e.g.,
- projects/myproject/locations/us
+ Parent resource that identifies admin project and location
+ e.g., ``projects/myproject/locations/us``
capacity_commitment_ids (Sequence[str]):
Ids of capacity commitments to merge.
These capacity commitments must exist under
admin project and location specified in the
parent.
+ ID is the last portion of capacity commitment
+ name e.g., 'abc' for
+ projects/myproject/locations/US/capacityCommitments/abc
"""
parent = proto.Field(proto.STRING, number=1)
+
capacity_commitment_ids = proto.RepeatedField(proto.STRING, number=2)
@@ -471,9 +493,12 @@ class State(proto.Enum):
ACTIVE = 2
name = proto.Field(proto.STRING, number=1)
+
assignee = proto.Field(proto.STRING, number=4)
- job_type = proto.Field(proto.ENUM, number=3, enum=JobType)
- state = proto.Field(proto.ENUM, number=6, enum=State)
+
+ job_type = proto.Field(proto.ENUM, number=3, enum=JobType,)
+
+ state = proto.Field(proto.ENUM, number=6, enum=State,)
class CreateAssignmentRequest(proto.Message):
@@ -491,7 +516,8 @@ class CreateAssignmentRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
- assignment = proto.Field(proto.MESSAGE, number=2, message=Assignment)
+
+ assignment = proto.Field(proto.MESSAGE, number=2, message=Assignment,)
class ListAssignmentsRequest(proto.Message):
@@ -516,7 +542,9 @@ class ListAssignmentsRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
page_size = proto.Field(proto.INT32, number=2)
+
page_token = proto.Field(proto.STRING, number=3)
@@ -537,7 +565,8 @@ class ListAssignmentsResponse(proto.Message):
def raw_page(self):
return self
- assignments = proto.RepeatedField(proto.MESSAGE, number=1, message=Assignment)
+ assignments = proto.RepeatedField(proto.MESSAGE, number=1, message=Assignment,)
+
next_page_token = proto.Field(proto.STRING, number=2)
@@ -564,9 +593,9 @@ class SearchAssignmentsRequest(proto.Message):
Attributes:
parent (str):
- Required. The resource name of the admin
- project(containing project and location), e.g.:
- "projects/myproject/locations/US".
+ Required. The resource name of the admin project(containing
+ project and location), e.g.:
+ ``projects/myproject/locations/US``.
query (str):
Please specify resource name as assignee in the query.
@@ -584,8 +613,11 @@ class SearchAssignmentsRequest(proto.Message):
"""
parent = proto.Field(proto.STRING, number=1)
+
query = proto.Field(proto.STRING, number=2)
+
page_size = proto.Field(proto.INT32, number=3)
+
page_token = proto.Field(proto.STRING, number=4)
@@ -606,7 +638,8 @@ class SearchAssignmentsResponse(proto.Message):
def raw_page(self):
return self
- assignments = proto.RepeatedField(proto.MESSAGE, number=1, message=Assignment)
+ assignments = proto.RepeatedField(proto.MESSAGE, number=1, message=Assignment,)
+
next_page_token = proto.Field(proto.STRING, number=2)
@@ -631,6 +664,7 @@ class MoveAssignmentRequest(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
+
destination_id = proto.Field(proto.STRING, number=3)
@@ -650,7 +684,9 @@ class BiReservation(proto.Message):
"""
name = proto.Field(proto.STRING, number=1)
- update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp)
+
+ update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,)
+
size = proto.Field(proto.INT64, number=4)
@@ -677,8 +713,9 @@ class UpdateBiReservationRequest(proto.Message):
request.
"""
- bi_reservation = proto.Field(proto.MESSAGE, number=1, message=BiReservation)
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask)
+ bi_reservation = proto.Field(proto.MESSAGE, number=1, message=BiReservation,)
+
+ update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/noxfile.py b/noxfile.py
index e69f5409..cf7b7cd2 100644
--- a/noxfile.py
+++ b/noxfile.py
@@ -23,14 +23,15 @@
import nox
-BLACK_VERSION = "black==19.3b0"
+BLACK_VERSION = "black==19.10b0"
BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"]
-if os.path.exists("samples"):
- BLACK_PATHS.append("samples")
+DEFAULT_PYTHON_VERSION = "3.8"
+SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"]
+UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"]
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint(session):
"""Run linters.
@@ -38,7 +39,9 @@ def lint(session):
serious code quality issues.
"""
session.install("flake8", BLACK_VERSION)
- session.run("black", "--check", *BLACK_PATHS)
+ session.run(
+ "black", "--check", *BLACK_PATHS,
+ )
session.run("flake8", "google", "tests")
@@ -53,10 +56,12 @@ def blacken(session):
check the state of the `gcp_ubuntu_config` we use for that Kokoro run.
"""
session.install(BLACK_VERSION)
- session.run("black", *BLACK_PATHS)
+ session.run(
+ "black", *BLACK_PATHS,
+ )
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint_setup_py(session):
"""Verify that setup.py is valid (including RST check)."""
session.install("docutils", "pygments")
@@ -65,6 +70,8 @@ def lint_setup_py(session):
def default(session):
# Install all test dependencies, then install this package in-place.
+ session.install("asyncmock", "pytest-asyncio")
+
session.install("mock", "pytest", "pytest-cov")
session.install("-e", ".")
@@ -84,17 +91,21 @@ def default(session):
)
-@nox.session(python=["3.6", "3.7", "3.8"])
+@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)
def unit(session):
"""Run the unit test suite."""
default(session)
-@nox.session(python=["3.7"])
+@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS)
def system(session):
"""Run the system test suite."""
system_test_path = os.path.join("tests", "system.py")
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")
@@ -110,7 +121,9 @@ def system(session):
# Install all test dependencies, then install this package into the
# virtualenv's dist-packages.
- session.install("mock", "pytest", "google-cloud-testutils")
+ session.install(
+ "mock", "pytest", "google-cloud-testutils",
+ )
session.install("-e", ".")
# Run py.test against the system tests.
@@ -120,7 +133,7 @@ def system(session):
session.run("py.test", "--quiet", system_test_folder_path, *session.posargs)
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def cover(session):
"""Run the final coverage report.
@@ -133,7 +146,7 @@ def cover(session):
session.run("coverage", "erase")
-@nox.session(python="3.7")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def docs(session):
"""Build the docs for this library."""
@@ -153,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/decrypt-secrets.sh b/scripts/decrypt-secrets.sh
new file mode 100755
index 00000000..ff599eb2
--- /dev/null
+++ b/scripts/decrypt-secrets.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+
+# Copyright 2015 Google Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+ROOT=$( dirname "$DIR" )
+
+# Work from the project root.
+cd $ROOT
+
+# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources.
+PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}"
+
+gcloud secrets versions access latest --secret="python-docs-samples-test-env" \
+ > testing/test-env.sh
+gcloud secrets versions access latest \
+ --secret="python-docs-samples-service-account" \
+ > testing/service-account.json
+gcloud secrets versions access latest \
+ --secret="python-docs-samples-client-secrets" \
+ > testing/client-secrets.json
\ No newline at end of file
diff --git a/scripts/fixup_reservation_v1_keywords.py b/scripts/fixup_reservation_v1_keywords.py
new file mode 100644
index 00000000..598edc38
--- /dev/null
+++ b/scripts/fixup_reservation_v1_keywords.py
@@ -0,0 +1,196 @@
+# -*- 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 reservationCallTransformer(cst.CSTTransformer):
+ CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
+ METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
+ 'create_assignment': ('parent', 'assignment', ),
+ 'create_capacity_commitment': ('parent', 'capacity_commitment', 'enforce_single_admin_project_per_org', ),
+ 'create_reservation': ('parent', 'reservation_id', 'reservation', ),
+ 'delete_assignment': ('name', ),
+ 'delete_capacity_commitment': ('name', ),
+ 'delete_reservation': ('name', ),
+ 'get_bi_reservation': ('name', ),
+ 'get_capacity_commitment': ('name', ),
+ 'get_reservation': ('name', ),
+ 'list_assignments': ('parent', 'page_size', 'page_token', ),
+ 'list_capacity_commitments': ('parent', 'page_size', 'page_token', ),
+ 'list_reservations': ('parent', 'page_size', 'page_token', ),
+ 'merge_capacity_commitments': ('parent', 'capacity_commitment_ids', ),
+ 'move_assignment': ('name', 'destination_id', ),
+ 'search_assignments': ('parent', 'query', 'page_size', 'page_token', ),
+ 'split_capacity_commitment': ('name', 'slot_count', ),
+ 'update_bi_reservation': ('bi_reservation', 'update_mask', ),
+ 'update_capacity_commitment': ('capacity_commitment', 'update_mask', ),
+ 'update_reservation': ('reservation', '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=reservationCallTransformer(),
+):
+ """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 reservation client library.
+
+The existing sources are NOT overwritten but are copied to output_dir with changes made.
+
+Note: This tool operates at a best-effort level at converting positional
+ parameters in client method calls to keyword based parameters.
+ Cases where it WILL FAIL include
+ A) * or ** expansion in a method call.
+ B) Calls via function or method alias (includes free function calls)
+ C) Indirect or dispatched calls (e.g. the method is looked up dynamically)
+
+ These all constitute false negatives. The tool will also detect false
+ positives when an API method shares a name with another method.
+""")
+ parser.add_argument(
+ '-d',
+ '--input-directory',
+ required=True,
+ dest='input_dir',
+ help='the input directory to walk for python files to fix up',
+ )
+ parser.add_argument(
+ '-o',
+ '--output-directory',
+ required=True,
+ dest='output_dir',
+ help='the directory to output files fixed via un-flattening',
+ )
+ args = parser.parse_args()
+ input_dir = pathlib.Path(args.input_dir)
+ output_dir = pathlib.Path(args.output_dir)
+ if not input_dir.is_dir():
+ print(
+ f"input directory '{input_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if not output_dir.is_dir():
+ print(
+ f"output directory '{output_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if os.listdir(output_dir):
+ print(
+ f"output directory '{output_dir}' is not empty",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ fix_files(input_dir, output_dir)
diff --git a/scripts/readme-gen/readme_gen.py b/scripts/readme-gen/readme_gen.py
new file mode 100644
index 00000000..d309d6e9
--- /dev/null
+++ b/scripts/readme-gen/readme_gen.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+
+# Copyright 2016 Google Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Generates READMEs using configuration defined in yaml."""
+
+import argparse
+import io
+import os
+import subprocess
+
+import jinja2
+import yaml
+
+
+jinja_env = jinja2.Environment(
+ trim_blocks=True,
+ loader=jinja2.FileSystemLoader(
+ os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates'))))
+
+README_TMPL = jinja_env.get_template('README.tmpl.rst')
+
+
+def get_help(file):
+ return subprocess.check_output(['python', file, '--help']).decode()
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('source')
+ parser.add_argument('--destination', default='README.rst')
+
+ args = parser.parse_args()
+
+ source = os.path.abspath(args.source)
+ root = os.path.dirname(source)
+ destination = os.path.join(root, args.destination)
+
+ jinja_env.globals['get_help'] = get_help
+
+ with io.open(source, 'r') as f:
+ config = yaml.load(f)
+
+ # This allows get_help to execute in the right directory.
+ os.chdir(root)
+
+ output = README_TMPL.render(config)
+
+ with io.open(destination, 'w') as f:
+ f.write(output)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/readme-gen/templates/README.tmpl.rst b/scripts/readme-gen/templates/README.tmpl.rst
new file mode 100644
index 00000000..4fd23976
--- /dev/null
+++ b/scripts/readme-gen/templates/README.tmpl.rst
@@ -0,0 +1,87 @@
+{# The following line is a lie. BUT! Once jinja2 is done with it, it will
+ become truth! #}
+.. This file is automatically generated. Do not edit this file directly.
+
+{{product.name}} Python Samples
+===============================================================================
+
+.. image:: https://gstatic.com/cloudssh/images/open-btn.png
+ :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/README.rst
+
+
+This directory contains samples for {{product.name}}. {{product.description}}
+
+{{description}}
+
+.. _{{product.name}}: {{product.url}}
+
+{% if required_api_url %}
+To run the sample, you need to enable the API at: {{required_api_url}}
+{% endif %}
+
+{% if required_role %}
+To run the sample, you need to have `{{required_role}}` role.
+{% endif %}
+
+{{other_required_steps}}
+
+{% if setup %}
+Setup
+-------------------------------------------------------------------------------
+
+{% for section in setup %}
+
+{% include section + '.tmpl.rst' %}
+
+{% endfor %}
+{% endif %}
+
+{% if samples %}
+Samples
+-------------------------------------------------------------------------------
+
+{% for sample in samples %}
+{{sample.name}}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+{% if not sample.hide_cloudshell_button %}
+.. image:: https://gstatic.com/cloudssh/images/open-btn.png
+ :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor={{folder}}/{{sample.file}},{{folder}}/README.rst
+{% endif %}
+
+
+{{sample.description}}
+
+To run this sample:
+
+.. code-block:: bash
+
+ $ python {{sample.file}}
+{% if sample.show_help %}
+
+ {{get_help(sample.file)|indent}}
+{% endif %}
+
+
+{% endfor %}
+{% endif %}
+
+{% if cloud_client_library %}
+
+The client library
+-------------------------------------------------------------------------------
+
+This sample uses the `Google Cloud Client Library for Python`_.
+You can read the documentation for more details on API usage and use GitHub
+to `browse the source`_ and `report issues`_.
+
+.. _Google Cloud Client Library for Python:
+ https://googlecloudplatform.github.io/google-cloud-python/
+.. _browse the source:
+ https://github.com/GoogleCloudPlatform/google-cloud-python
+.. _report issues:
+ https://github.com/GoogleCloudPlatform/google-cloud-python/issues
+
+{% endif %}
+
+.. _Google Cloud SDK: https://cloud.google.com/sdk/
\ No newline at end of file
diff --git a/scripts/readme-gen/templates/auth.tmpl.rst b/scripts/readme-gen/templates/auth.tmpl.rst
new file mode 100644
index 00000000..1446b94a
--- /dev/null
+++ b/scripts/readme-gen/templates/auth.tmpl.rst
@@ -0,0 +1,9 @@
+Authentication
+++++++++++++++
+
+This sample requires you to have authentication setup. Refer to the
+`Authentication Getting Started Guide`_ for instructions on setting up
+credentials for applications.
+
+.. _Authentication Getting Started Guide:
+ https://cloud.google.com/docs/authentication/getting-started
diff --git a/scripts/readme-gen/templates/auth_api_key.tmpl.rst b/scripts/readme-gen/templates/auth_api_key.tmpl.rst
new file mode 100644
index 00000000..11957ce2
--- /dev/null
+++ b/scripts/readme-gen/templates/auth_api_key.tmpl.rst
@@ -0,0 +1,14 @@
+Authentication
+++++++++++++++
+
+Authentication for this service is done via an `API Key`_. To obtain an API
+Key:
+
+1. Open the `Cloud Platform Console`_
+2. Make sure that billing is enabled for your project.
+3. From the **Credentials** page, create a new **API Key** or use an existing
+ one for your project.
+
+.. _API Key:
+ https://developers.google.com/api-client-library/python/guide/aaa_apikeys
+.. _Cloud Console: https://console.cloud.google.com/project?_
diff --git a/scripts/readme-gen/templates/install_deps.tmpl.rst b/scripts/readme-gen/templates/install_deps.tmpl.rst
new file mode 100644
index 00000000..a0406dba
--- /dev/null
+++ b/scripts/readme-gen/templates/install_deps.tmpl.rst
@@ -0,0 +1,29 @@
+Install Dependencies
+++++++++++++++++++++
+
+#. Clone python-docs-samples and change directory to the sample directory you want to use.
+
+ .. code-block:: bash
+
+ $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
+
+#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions.
+
+ .. _Python Development Environment Setup Guide:
+ https://cloud.google.com/python/setup
+
+#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+.
+
+ .. code-block:: bash
+
+ $ virtualenv env
+ $ source env/bin/activate
+
+#. Install the dependencies needed to run the samples.
+
+ .. code-block:: bash
+
+ $ pip install -r requirements.txt
+
+.. _pip: https://pip.pypa.io/
+.. _virtualenv: https://virtualenv.pypa.io/
diff --git a/scripts/readme-gen/templates/install_portaudio.tmpl.rst b/scripts/readme-gen/templates/install_portaudio.tmpl.rst
new file mode 100644
index 00000000..5ea33d18
--- /dev/null
+++ b/scripts/readme-gen/templates/install_portaudio.tmpl.rst
@@ -0,0 +1,35 @@
+Install PortAudio
++++++++++++++++++
+
+Install `PortAudio`_. This is required by the `PyAudio`_ library to stream
+audio from your computer's microphone. PyAudio depends on PortAudio for cross-platform compatibility, and is installed differently depending on the
+platform.
+
+* For Mac OS X, you can use `Homebrew`_::
+
+ brew install portaudio
+
+ **Note**: if you encounter an error when running `pip install` that indicates
+ it can't find `portaudio.h`, try running `pip install` with the following
+ flags::
+
+ pip install --global-option='build_ext' \
+ --global-option='-I/usr/local/include' \
+ --global-option='-L/usr/local/lib' \
+ pyaudio
+
+* For Debian / Ubuntu Linux::
+
+ apt-get install portaudio19-dev python-all-dev
+
+* Windows may work without having to install PortAudio explicitly (it will get
+ installed with PyAudio).
+
+For more details, see the `PyAudio installation`_ page.
+
+
+.. _PyAudio: https://people.csail.mit.edu/hubert/pyaudio/
+.. _PortAudio: http://www.portaudio.com/
+.. _PyAudio installation:
+ https://people.csail.mit.edu/hubert/pyaudio/#downloads
+.. _Homebrew: http://brew.sh
diff --git a/setup.py b/setup.py
index 01a96e8b..761c9b1e 100644
--- a/setup.py
+++ b/setup.py
@@ -42,11 +42,8 @@
platforms="Posix; MacOS X; Windows",
include_package_data=True,
install_requires=(
- "google-auth >= 1.14.0",
- "google-api-core >= 1.8.0, < 2.0.0dev",
- "googleapis-common-protos >= 1.5.8",
- "grpcio >= 1.10.0",
- "proto-plus >= 0.4.0",
+ "google-api-core[grpc] >= 1.22.0, < 2.0.0dev",
+ "proto-plus >= 1.4.0",
),
python_requires=">=3.6",
setup_requires=["libcst >= 0.2.5"],
diff --git a/synth.metadata b/synth.metadata
index 12134361..188def38 100644
--- a/synth.metadata
+++ b/synth.metadata
@@ -3,30 +3,30 @@
{
"git": {
"name": ".",
- "remote": "https://github.com/googleapis/python-bigquery-reservation.git",
- "sha": "4210d3c3e198d5c2220b9590e77df4f5712109b6"
+ "remote": "git@github.com:googleapis/python-bigquery-reservation.git",
+ "sha": "427dfea24639fcdf1b78197854d8f93b09a4495f"
}
},
{
"git": {
"name": "googleapis",
"remote": "https://github.com/googleapis/googleapis.git",
- "sha": "eafa840ceec23b44a5c21670288107c661252711",
- "internalRef": "313488995"
+ "sha": "5ad09e867a8f1faa19fbd674e51fa9c3f5fe2770",
+ "internalRef": "326514554"
}
},
{
"git": {
"name": "synthtool",
"remote": "https://github.com/googleapis/synthtool.git",
- "sha": "71b8a272549c06b5768d00fa48d3ae990e871bec"
+ "sha": "d3049e66447b44dc10579e461d5e08e0e3838edd"
}
},
{
"git": {
"name": "synthtool",
"remote": "https://github.com/googleapis/synthtool.git",
- "sha": "71b8a272549c06b5768d00fa48d3ae990e871bec"
+ "sha": "d3049e66447b44dc10579e461d5e08e0e3838edd"
}
}
],
diff --git a/synth.py b/synth.py
index 279fe9ca..0d8c8df2 100644
--- a/synth.py
+++ b/synth.py
@@ -25,36 +25,24 @@
# ----------------------------------------------------------------------------
# Generate access approval GAPIC layer
# ----------------------------------------------------------------------------
-library = gapic.py_library(
- "bigquery/reservation", "v1"
-)
+library = gapic.py_library("bigquery/reservation", "v1")
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()
+s.replace(
+ ["google/cloud/bigquery/reservation_v1/services/reservation_service/client.py",
+ "google/cloud/bigquery/reservation_v1/services/reservation_service/async_client.py"],
+ "assignee=organizations/456``",
+ "assignee=organizations/456``\n",
+)
# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
-templated_files = common.py_library(cov_level=100)
+templated_files = common.py_library(cov_level=100, microgenerator=True)
s.move(
- templated_files, excludes=[".coveragerc"]
-) # the microgenerator has a good coveragerc file
-
-# Remove 2.7 and 3.5 tests from noxfile.py
-s.replace("noxfile.py", """\["2\.7", """, "[")
-s.replace("noxfile.py", """"3.5", """, "")
-s.replace(
- "google/cloud/bigquery/reservation_v1/services/reservation_service/client.py",
- "assignee=organizations/456``", "assignee=organizations/456``\n")
-
-# Expand flake errors permitted to accomodate the Microgenerator
-# TODO: remove extra error codes once issues below are resolved
-# F401: https://github.com/googleapis/gapic-generator-python/issues/324
-# F841: local variable 'client'/'response' is assigned to but never use
-s.replace(".flake8", "ignore = .*", "ignore = E203, E266, E501, W503, F401, F841")
-
+ templated_files,
+ excludes=[".coveragerc"], # the microgenerator has a good coveragerc file
+)
s.shell.run(["nox", "-s", "blacken"], hide_output=False)
diff --git a/testing/.gitignore b/testing/.gitignore
new file mode 100644
index 00000000..b05fbd63
--- /dev/null
+++ b/testing/.gitignore
@@ -0,0 +1,3 @@
+test-env.sh
+service-account.json
+client-secrets.json
\ No newline at end of file
diff --git a/tests/unit/gapic/reservation_v1/__init__.py b/tests/unit/gapic/reservation_v1/__init__.py
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/tests/unit/gapic/reservation_v1/__init__.py
@@ -0,0 +1 @@
+
diff --git a/tests/unit/gapic/reservation_v1/test_reservation_service.py b/tests/unit/gapic/reservation_v1/test_reservation_service.py
new file mode 100644
index 00000000..ad061b70
--- /dev/null
+++ b/tests/unit/gapic/reservation_v1/test_reservation_service.py
@@ -0,0 +1,5632 @@
+# -*- 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 gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.bigquery.reservation_v1.services.reservation_service import (
+ ReservationServiceAsyncClient,
+)
+from google.cloud.bigquery.reservation_v1.services.reservation_service import (
+ ReservationServiceClient,
+)
+from google.cloud.bigquery.reservation_v1.services.reservation_service import pagers
+from google.cloud.bigquery.reservation_v1.services.reservation_service import transports
+from google.cloud.bigquery.reservation_v1.types import reservation
+from google.cloud.bigquery.reservation_v1.types import reservation as gcbr_reservation
+from google.oauth2 import service_account
+from google.protobuf import any_pb2 as any # 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 google.rpc import status_pb2 as status # 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 ReservationServiceClient._get_default_mtls_endpoint(None) is None
+ assert (
+ ReservationServiceClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ ReservationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ ReservationServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ ReservationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ ReservationServiceClient._get_default_mtls_endpoint(non_googleapi)
+ == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [ReservationServiceClient, ReservationServiceAsyncClient]
+)
+def test_reservation_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 == "bigqueryreservation.googleapis.com:443"
+
+
+def test_reservation_service_client_get_transport_class():
+ transport = ReservationServiceClient.get_transport_class()
+ assert transport == transports.ReservationServiceGrpcTransport
+
+ transport = ReservationServiceClient.get_transport_class("grpc")
+ assert transport == transports.ReservationServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (ReservationServiceClient, transports.ReservationServiceGrpcTransport, "grpc"),
+ (
+ ReservationServiceAsyncClient,
+ transports.ReservationServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+@mock.patch.object(
+ ReservationServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(ReservationServiceClient),
+)
+@mock.patch.object(
+ ReservationServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(ReservationServiceAsyncClient),
+)
+def test_reservation_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(ReservationServiceClient, "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(ReservationServiceClient, "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",
+ [
+ (ReservationServiceClient, transports.ReservationServiceGrpcTransport, "grpc"),
+ (
+ ReservationServiceAsyncClient,
+ transports.ReservationServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_reservation_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",
+ [
+ (ReservationServiceClient, transports.ReservationServiceGrpcTransport, "grpc"),
+ (
+ ReservationServiceAsyncClient,
+ transports.ReservationServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_reservation_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_reservation_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.bigquery.reservation_v1.services.reservation_service.transports.ReservationServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = ReservationServiceClient(
+ 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_create_reservation(
+ transport: str = "grpc", request_type=gcbr_reservation.CreateReservationRequest
+):
+ client = ReservationServiceClient(
+ 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_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcbr_reservation.Reservation(
+ name="name_value", slot_capacity=1391, ignore_idle_slots=True,
+ )
+
+ response = client.create_reservation(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == gcbr_reservation.CreateReservationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcbr_reservation.Reservation)
+
+ assert response.name == "name_value"
+
+ assert response.slot_capacity == 1391
+
+ assert response.ignore_idle_slots is True
+
+
+def test_create_reservation_from_dict():
+ test_create_reservation(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_create_reservation_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = gcbr_reservation.CreateReservationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcbr_reservation.Reservation(
+ name="name_value", slot_capacity=1391, ignore_idle_slots=True,
+ )
+ )
+
+ response = await client.create_reservation(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, gcbr_reservation.Reservation)
+
+ assert response.name == "name_value"
+
+ assert response.slot_capacity == 1391
+
+ assert response.ignore_idle_slots is True
+
+
+def test_create_reservation_field_headers():
+ client = ReservationServiceClient(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 = gcbr_reservation.CreateReservationRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_reservation), "__call__"
+ ) as call:
+ call.return_value = gcbr_reservation.Reservation()
+
+ client.create_reservation(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_reservation_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = gcbr_reservation.CreateReservationRequest()
+ 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_reservation), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcbr_reservation.Reservation()
+ )
+
+ await client.create_reservation(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_reservation_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcbr_reservation.Reservation()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.create_reservation(
+ parent="parent_value",
+ reservation=gcbr_reservation.Reservation(name="name_value"),
+ reservation_id="reservation_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].reservation == gcbr_reservation.Reservation(name="name_value")
+
+ assert args[0].reservation_id == "reservation_id_value"
+
+
+def test_create_reservation_flattened_error():
+ client = ReservationServiceClient(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_reservation(
+ gcbr_reservation.CreateReservationRequest(),
+ parent="parent_value",
+ reservation=gcbr_reservation.Reservation(name="name_value"),
+ reservation_id="reservation_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_reservation_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcbr_reservation.Reservation()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcbr_reservation.Reservation()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.create_reservation(
+ parent="parent_value",
+ reservation=gcbr_reservation.Reservation(name="name_value"),
+ reservation_id="reservation_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].reservation == gcbr_reservation.Reservation(name="name_value")
+
+ assert args[0].reservation_id == "reservation_id_value"
+
+
+@pytest.mark.asyncio
+async def test_create_reservation_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_reservation(
+ gcbr_reservation.CreateReservationRequest(),
+ parent="parent_value",
+ reservation=gcbr_reservation.Reservation(name="name_value"),
+ reservation_id="reservation_id_value",
+ )
+
+
+def test_list_reservations(
+ transport: str = "grpc", request_type=reservation.ListReservationsRequest
+):
+ client = ReservationServiceClient(
+ 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_reservations), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListReservationsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_reservations(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.ListReservationsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListReservationsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_reservations_from_dict():
+ test_list_reservations(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_list_reservations_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.ListReservationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_reservations), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListReservationsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+
+ response = await client.list_reservations(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.ListReservationsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_reservations_field_headers():
+ client = ReservationServiceClient(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 = reservation.ListReservationsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_reservations), "__call__"
+ ) as call:
+ call.return_value = reservation.ListReservationsResponse()
+
+ client.list_reservations(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_reservations_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.ListReservationsRequest()
+ 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_reservations), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListReservationsResponse()
+ )
+
+ await client.list_reservations(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_reservations_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_reservations), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListReservationsResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_reservations(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_reservations_flattened_error():
+ client = ReservationServiceClient(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_reservations(
+ reservation.ListReservationsRequest(), parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_reservations_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_reservations), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListReservationsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListReservationsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_reservations(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_reservations_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_reservations(
+ reservation.ListReservationsRequest(), parent="parent_value",
+ )
+
+
+def test_list_reservations_pager():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_reservations), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListReservationsResponse(
+ reservations=[
+ reservation.Reservation(),
+ reservation.Reservation(),
+ reservation.Reservation(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[], next_page_token="def",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(),], next_page_token="ghi",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(), reservation.Reservation(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_reservations(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, reservation.Reservation) for i in results)
+
+
+def test_list_reservations_pages():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_reservations), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListReservationsResponse(
+ reservations=[
+ reservation.Reservation(),
+ reservation.Reservation(),
+ reservation.Reservation(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[], next_page_token="def",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(),], next_page_token="ghi",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(), reservation.Reservation(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_reservations(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_reservations_async_pager():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_reservations),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListReservationsResponse(
+ reservations=[
+ reservation.Reservation(),
+ reservation.Reservation(),
+ reservation.Reservation(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[], next_page_token="def",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(),], next_page_token="ghi",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(), reservation.Reservation(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_reservations(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, reservation.Reservation) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_reservations_async_pages():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_reservations),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListReservationsResponse(
+ reservations=[
+ reservation.Reservation(),
+ reservation.Reservation(),
+ reservation.Reservation(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[], next_page_token="def",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(),], next_page_token="ghi",
+ ),
+ reservation.ListReservationsResponse(
+ reservations=[reservation.Reservation(), reservation.Reservation(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.list_reservations(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_reservation(
+ transport: str = "grpc", request_type=reservation.GetReservationRequest
+):
+ client = ReservationServiceClient(
+ 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_reservation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Reservation(
+ name="name_value", slot_capacity=1391, ignore_idle_slots=True,
+ )
+
+ response = client.get_reservation(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.GetReservationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.Reservation)
+
+ assert response.name == "name_value"
+
+ assert response.slot_capacity == 1391
+
+ assert response.ignore_idle_slots is True
+
+
+def test_get_reservation_from_dict():
+ test_get_reservation(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_get_reservation_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.GetReservationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Reservation(
+ name="name_value", slot_capacity=1391, ignore_idle_slots=True,
+ )
+ )
+
+ response = await client.get_reservation(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, reservation.Reservation)
+
+ assert response.name == "name_value"
+
+ assert response.slot_capacity == 1391
+
+ assert response.ignore_idle_slots is True
+
+
+def test_get_reservation_field_headers():
+ client = ReservationServiceClient(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 = reservation.GetReservationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.get_reservation), "__call__") as call:
+ call.return_value = reservation.Reservation()
+
+ client.get_reservation(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_reservation_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.GetReservationRequest()
+ 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_reservation), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Reservation()
+ )
+
+ await client.get_reservation(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_reservation_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.get_reservation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Reservation()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_reservation(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_reservation_flattened_error():
+ client = ReservationServiceClient(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_reservation(
+ reservation.GetReservationRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_reservation_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Reservation()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Reservation()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_reservation(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_reservation_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_reservation(
+ reservation.GetReservationRequest(), name="name_value",
+ )
+
+
+def test_delete_reservation(
+ transport: str = "grpc", request_type=reservation.DeleteReservationRequest
+):
+ client = ReservationServiceClient(
+ 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_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.delete_reservation(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.DeleteReservationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_reservation_from_dict():
+ test_delete_reservation(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_delete_reservation_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.DeleteReservationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ response = await client.delete_reservation(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 response is None
+
+
+def test_delete_reservation_field_headers():
+ client = ReservationServiceClient(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 = reservation.DeleteReservationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_reservation), "__call__"
+ ) as call:
+ call.return_value = None
+
+ client.delete_reservation(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_reservation_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.DeleteReservationRequest()
+ 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_reservation), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ await client.delete_reservation(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_reservation_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_reservation(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_reservation_flattened_error():
+ client = ReservationServiceClient(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_reservation(
+ reservation.DeleteReservationRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_reservation_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_reservation(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_reservation_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_reservation(
+ reservation.DeleteReservationRequest(), name="name_value",
+ )
+
+
+def test_update_reservation(
+ transport: str = "grpc", request_type=gcbr_reservation.UpdateReservationRequest
+):
+ client = ReservationServiceClient(
+ 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_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcbr_reservation.Reservation(
+ name="name_value", slot_capacity=1391, ignore_idle_slots=True,
+ )
+
+ response = client.update_reservation(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == gcbr_reservation.UpdateReservationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcbr_reservation.Reservation)
+
+ assert response.name == "name_value"
+
+ assert response.slot_capacity == 1391
+
+ assert response.ignore_idle_slots is True
+
+
+def test_update_reservation_from_dict():
+ test_update_reservation(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_update_reservation_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = gcbr_reservation.UpdateReservationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcbr_reservation.Reservation(
+ name="name_value", slot_capacity=1391, ignore_idle_slots=True,
+ )
+ )
+
+ response = await client.update_reservation(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, gcbr_reservation.Reservation)
+
+ assert response.name == "name_value"
+
+ assert response.slot_capacity == 1391
+
+ assert response.ignore_idle_slots is True
+
+
+def test_update_reservation_field_headers():
+ client = ReservationServiceClient(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 = gcbr_reservation.UpdateReservationRequest()
+ request.reservation.name = "reservation.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_reservation), "__call__"
+ ) as call:
+ call.return_value = gcbr_reservation.Reservation()
+
+ client.update_reservation(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", "reservation.name=reservation.name/value",) in kw[
+ "metadata"
+ ]
+
+
+@pytest.mark.asyncio
+async def test_update_reservation_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = gcbr_reservation.UpdateReservationRequest()
+ request.reservation.name = "reservation.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_reservation), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcbr_reservation.Reservation()
+ )
+
+ await client.update_reservation(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", "reservation.name=reservation.name/value",) in kw[
+ "metadata"
+ ]
+
+
+def test_update_reservation_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcbr_reservation.Reservation()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_reservation(
+ reservation=gcbr_reservation.Reservation(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].reservation == gcbr_reservation.Reservation(name="name_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_reservation_flattened_error():
+ client = ReservationServiceClient(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_reservation(
+ gcbr_reservation.UpdateReservationRequest(),
+ reservation=gcbr_reservation.Reservation(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_reservation_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcbr_reservation.Reservation()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcbr_reservation.Reservation()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_reservation(
+ reservation=gcbr_reservation.Reservation(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].reservation == gcbr_reservation.Reservation(name="name_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_reservation_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_reservation(
+ gcbr_reservation.UpdateReservationRequest(),
+ reservation=gcbr_reservation.Reservation(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_create_capacity_commitment(
+ transport: str = "grpc", request_type=reservation.CreateCapacityCommitmentRequest
+):
+ client = ReservationServiceClient(
+ 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_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+
+ response = client.create_capacity_commitment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.CreateCapacityCommitmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_create_capacity_commitment_from_dict():
+ test_create_capacity_commitment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_create_capacity_commitment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.CreateCapacityCommitmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+ )
+
+ response = await client.create_capacity_commitment(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, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_create_capacity_commitment_field_headers():
+ client = ReservationServiceClient(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 = reservation.CreateCapacityCommitmentRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = reservation.CapacityCommitment()
+
+ client.create_capacity_commitment(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_capacity_commitment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.CreateCapacityCommitmentRequest()
+ 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_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+
+ await client.create_capacity_commitment(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_capacity_commitment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.create_capacity_commitment(
+ parent="parent_value",
+ capacity_commitment=reservation.CapacityCommitment(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].capacity_commitment == reservation.CapacityCommitment(
+ name="name_value"
+ )
+
+
+def test_create_capacity_commitment_flattened_error():
+ client = ReservationServiceClient(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_capacity_commitment(
+ reservation.CreateCapacityCommitmentRequest(),
+ parent="parent_value",
+ capacity_commitment=reservation.CapacityCommitment(name="name_value"),
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_capacity_commitment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.create_capacity_commitment(
+ parent="parent_value",
+ capacity_commitment=reservation.CapacityCommitment(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].capacity_commitment == reservation.CapacityCommitment(
+ name="name_value"
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_capacity_commitment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_capacity_commitment(
+ reservation.CreateCapacityCommitmentRequest(),
+ parent="parent_value",
+ capacity_commitment=reservation.CapacityCommitment(name="name_value"),
+ )
+
+
+def test_list_capacity_commitments(
+ transport: str = "grpc", request_type=reservation.ListCapacityCommitmentsRequest
+):
+ client = ReservationServiceClient(
+ 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_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListCapacityCommitmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_capacity_commitments(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.ListCapacityCommitmentsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListCapacityCommitmentsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_capacity_commitments_from_dict():
+ test_list_capacity_commitments(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_list_capacity_commitments_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.ListCapacityCommitmentsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListCapacityCommitmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+
+ response = await client.list_capacity_commitments(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.ListCapacityCommitmentsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_capacity_commitments_field_headers():
+ client = ReservationServiceClient(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 = reservation.ListCapacityCommitmentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_capacity_commitments), "__call__"
+ ) as call:
+ call.return_value = reservation.ListCapacityCommitmentsResponse()
+
+ client.list_capacity_commitments(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_capacity_commitments_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.ListCapacityCommitmentsRequest()
+ 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_capacity_commitments), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListCapacityCommitmentsResponse()
+ )
+
+ await client.list_capacity_commitments(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_capacity_commitments_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListCapacityCommitmentsResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_capacity_commitments(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_capacity_commitments_flattened_error():
+ client = ReservationServiceClient(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_capacity_commitments(
+ reservation.ListCapacityCommitmentsRequest(), parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_capacity_commitments_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListCapacityCommitmentsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListCapacityCommitmentsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_capacity_commitments(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_capacity_commitments_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_capacity_commitments(
+ reservation.ListCapacityCommitmentsRequest(), parent="parent_value",
+ )
+
+
+def test_list_capacity_commitments_pager():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_capacity_commitments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[], next_page_token="def",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[reservation.CapacityCommitment(),],
+ next_page_token="ghi",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_capacity_commitments(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, reservation.CapacityCommitment) for i in results)
+
+
+def test_list_capacity_commitments_pages():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_capacity_commitments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[], next_page_token="def",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[reservation.CapacityCommitment(),],
+ next_page_token="ghi",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_capacity_commitments(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_capacity_commitments_async_pager():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_capacity_commitments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[], next_page_token="def",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[reservation.CapacityCommitment(),],
+ next_page_token="ghi",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_capacity_commitments(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, reservation.CapacityCommitment) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_capacity_commitments_async_pages():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_capacity_commitments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[], next_page_token="def",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[reservation.CapacityCommitment(),],
+ next_page_token="ghi",
+ ),
+ reservation.ListCapacityCommitmentsResponse(
+ capacity_commitments=[
+ reservation.CapacityCommitment(),
+ reservation.CapacityCommitment(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.list_capacity_commitments(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_capacity_commitment(
+ transport: str = "grpc", request_type=reservation.GetCapacityCommitmentRequest
+):
+ client = ReservationServiceClient(
+ 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_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+
+ response = client.get_capacity_commitment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.GetCapacityCommitmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_get_capacity_commitment_from_dict():
+ test_get_capacity_commitment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_get_capacity_commitment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.GetCapacityCommitmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+ )
+
+ response = await client.get_capacity_commitment(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, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_get_capacity_commitment_field_headers():
+ client = ReservationServiceClient(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 = reservation.GetCapacityCommitmentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = reservation.CapacityCommitment()
+
+ client.get_capacity_commitment(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_capacity_commitment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.GetCapacityCommitmentRequest()
+ 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_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+
+ await client.get_capacity_commitment(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_capacity_commitment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_capacity_commitment(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_capacity_commitment_flattened_error():
+ client = ReservationServiceClient(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_capacity_commitment(
+ reservation.GetCapacityCommitmentRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_capacity_commitment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_capacity_commitment(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_capacity_commitment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_capacity_commitment(
+ reservation.GetCapacityCommitmentRequest(), name="name_value",
+ )
+
+
+def test_delete_capacity_commitment(
+ transport: str = "grpc", request_type=reservation.DeleteCapacityCommitmentRequest
+):
+ client = ReservationServiceClient(
+ 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_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.delete_capacity_commitment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.DeleteCapacityCommitmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_capacity_commitment_from_dict():
+ test_delete_capacity_commitment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_delete_capacity_commitment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.DeleteCapacityCommitmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ response = await client.delete_capacity_commitment(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 response is None
+
+
+def test_delete_capacity_commitment_field_headers():
+ client = ReservationServiceClient(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 = reservation.DeleteCapacityCommitmentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = None
+
+ client.delete_capacity_commitment(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_capacity_commitment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.DeleteCapacityCommitmentRequest()
+ 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_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ await client.delete_capacity_commitment(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_capacity_commitment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_capacity_commitment(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_capacity_commitment_flattened_error():
+ client = ReservationServiceClient(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_capacity_commitment(
+ reservation.DeleteCapacityCommitmentRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_capacity_commitment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_capacity_commitment(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_capacity_commitment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_capacity_commitment(
+ reservation.DeleteCapacityCommitmentRequest(), name="name_value",
+ )
+
+
+def test_update_capacity_commitment(
+ transport: str = "grpc", request_type=reservation.UpdateCapacityCommitmentRequest
+):
+ client = ReservationServiceClient(
+ 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_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+
+ response = client.update_capacity_commitment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.UpdateCapacityCommitmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_update_capacity_commitment_from_dict():
+ test_update_capacity_commitment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_update_capacity_commitment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.UpdateCapacityCommitmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+ )
+
+ response = await client.update_capacity_commitment(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, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_update_capacity_commitment_field_headers():
+ client = ReservationServiceClient(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 = reservation.UpdateCapacityCommitmentRequest()
+ request.capacity_commitment.name = "capacity_commitment.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = reservation.CapacityCommitment()
+
+ client.update_capacity_commitment(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",
+ "capacity_commitment.name=capacity_commitment.name/value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_capacity_commitment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.UpdateCapacityCommitmentRequest()
+ request.capacity_commitment.name = "capacity_commitment.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+
+ await client.update_capacity_commitment(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",
+ "capacity_commitment.name=capacity_commitment.name/value",
+ ) in kw["metadata"]
+
+
+def test_update_capacity_commitment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_capacity_commitment(
+ capacity_commitment=reservation.CapacityCommitment(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].capacity_commitment == reservation.CapacityCommitment(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_capacity_commitment_flattened_error():
+ client = ReservationServiceClient(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_capacity_commitment(
+ reservation.UpdateCapacityCommitmentRequest(),
+ capacity_commitment=reservation.CapacityCommitment(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_capacity_commitment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_capacity_commitment(
+ capacity_commitment=reservation.CapacityCommitment(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].capacity_commitment == reservation.CapacityCommitment(
+ name="name_value"
+ )
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_capacity_commitment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_capacity_commitment(
+ reservation.UpdateCapacityCommitmentRequest(),
+ capacity_commitment=reservation.CapacityCommitment(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_split_capacity_commitment(
+ transport: str = "grpc", request_type=reservation.SplitCapacityCommitmentRequest
+):
+ client = ReservationServiceClient(
+ 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.split_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.SplitCapacityCommitmentResponse()
+
+ response = client.split_capacity_commitment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.SplitCapacityCommitmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.SplitCapacityCommitmentResponse)
+
+
+def test_split_capacity_commitment_from_dict():
+ test_split_capacity_commitment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_split_capacity_commitment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.SplitCapacityCommitmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.split_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.SplitCapacityCommitmentResponse()
+ )
+
+ response = await client.split_capacity_commitment(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, reservation.SplitCapacityCommitmentResponse)
+
+
+def test_split_capacity_commitment_field_headers():
+ client = ReservationServiceClient(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 = reservation.SplitCapacityCommitmentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.split_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = reservation.SplitCapacityCommitmentResponse()
+
+ client.split_capacity_commitment(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_split_capacity_commitment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.SplitCapacityCommitmentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.split_capacity_commitment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.SplitCapacityCommitmentResponse()
+ )
+
+ await client.split_capacity_commitment(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_split_capacity_commitment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.split_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.SplitCapacityCommitmentResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.split_capacity_commitment(
+ name="name_value", slot_count=1098,
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+ assert args[0].slot_count == 1098
+
+
+def test_split_capacity_commitment_flattened_error():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.split_capacity_commitment(
+ reservation.SplitCapacityCommitmentRequest(),
+ name="name_value",
+ slot_count=1098,
+ )
+
+
+@pytest.mark.asyncio
+async def test_split_capacity_commitment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.split_capacity_commitment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.SplitCapacityCommitmentResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.SplitCapacityCommitmentResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.split_capacity_commitment(
+ name="name_value", slot_count=1098,
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+ assert args[0].slot_count == 1098
+
+
+@pytest.mark.asyncio
+async def test_split_capacity_commitment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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.split_capacity_commitment(
+ reservation.SplitCapacityCommitmentRequest(),
+ name="name_value",
+ slot_count=1098,
+ )
+
+
+def test_merge_capacity_commitments(
+ transport: str = "grpc", request_type=reservation.MergeCapacityCommitmentsRequest
+):
+ client = ReservationServiceClient(
+ 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.merge_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+
+ response = client.merge_capacity_commitments(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.MergeCapacityCommitmentsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_merge_capacity_commitments_from_dict():
+ test_merge_capacity_commitments(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_merge_capacity_commitments_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.MergeCapacityCommitmentsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.merge_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment(
+ name="name_value",
+ slot_count=1098,
+ plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ state=reservation.CapacityCommitment.State.PENDING,
+ renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
+ )
+ )
+
+ response = await client.merge_capacity_commitments(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, reservation.CapacityCommitment)
+
+ assert response.name == "name_value"
+
+ assert response.slot_count == 1098
+
+ assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+ assert response.state == reservation.CapacityCommitment.State.PENDING
+
+ assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
+
+
+def test_merge_capacity_commitments_field_headers():
+ client = ReservationServiceClient(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 = reservation.MergeCapacityCommitmentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.merge_capacity_commitments), "__call__"
+ ) as call:
+ call.return_value = reservation.CapacityCommitment()
+
+ client.merge_capacity_commitments(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_merge_capacity_commitments_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.MergeCapacityCommitmentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.merge_capacity_commitments), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+
+ await client.merge_capacity_commitments(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_merge_capacity_commitments_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.merge_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.merge_capacity_commitments(
+ parent="parent_value",
+ capacity_commitment_ids=["capacity_commitment_ids_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].capacity_commitment_ids == ["capacity_commitment_ids_value"]
+
+
+def test_merge_capacity_commitments_flattened_error():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.merge_capacity_commitments(
+ reservation.MergeCapacityCommitmentsRequest(),
+ parent="parent_value",
+ capacity_commitment_ids=["capacity_commitment_ids_value"],
+ )
+
+
+@pytest.mark.asyncio
+async def test_merge_capacity_commitments_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.merge_capacity_commitments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.CapacityCommitment()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.CapacityCommitment()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.merge_capacity_commitments(
+ parent="parent_value",
+ capacity_commitment_ids=["capacity_commitment_ids_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].capacity_commitment_ids == ["capacity_commitment_ids_value"]
+
+
+@pytest.mark.asyncio
+async def test_merge_capacity_commitments_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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.merge_capacity_commitments(
+ reservation.MergeCapacityCommitmentsRequest(),
+ parent="parent_value",
+ capacity_commitment_ids=["capacity_commitment_ids_value"],
+ )
+
+
+def test_create_assignment(
+ transport: str = "grpc", request_type=reservation.CreateAssignmentRequest
+):
+ client = ReservationServiceClient(
+ 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_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Assignment(
+ name="name_value",
+ assignee="assignee_value",
+ job_type=reservation.Assignment.JobType.PIPELINE,
+ state=reservation.Assignment.State.PENDING,
+ )
+
+ response = client.create_assignment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.CreateAssignmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.Assignment)
+
+ assert response.name == "name_value"
+
+ assert response.assignee == "assignee_value"
+
+ assert response.job_type == reservation.Assignment.JobType.PIPELINE
+
+ assert response.state == reservation.Assignment.State.PENDING
+
+
+def test_create_assignment_from_dict():
+ test_create_assignment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_create_assignment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.CreateAssignmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Assignment(
+ name="name_value",
+ assignee="assignee_value",
+ job_type=reservation.Assignment.JobType.PIPELINE,
+ state=reservation.Assignment.State.PENDING,
+ )
+ )
+
+ response = await client.create_assignment(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, reservation.Assignment)
+
+ assert response.name == "name_value"
+
+ assert response.assignee == "assignee_value"
+
+ assert response.job_type == reservation.Assignment.JobType.PIPELINE
+
+ assert response.state == reservation.Assignment.State.PENDING
+
+
+def test_create_assignment_field_headers():
+ client = ReservationServiceClient(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 = reservation.CreateAssignmentRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_assignment), "__call__"
+ ) as call:
+ call.return_value = reservation.Assignment()
+
+ client.create_assignment(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_assignment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.CreateAssignmentRequest()
+ 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_assignment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Assignment()
+ )
+
+ await client.create_assignment(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_assignment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.create_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Assignment()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.create_assignment(
+ parent="parent_value", assignment=reservation.Assignment(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].assignment == reservation.Assignment(name="name_value")
+
+
+def test_create_assignment_flattened_error():
+ client = ReservationServiceClient(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_assignment(
+ reservation.CreateAssignmentRequest(),
+ parent="parent_value",
+ assignment=reservation.Assignment(name="name_value"),
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_assignment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.create_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Assignment()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Assignment()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.create_assignment(
+ parent="parent_value", assignment=reservation.Assignment(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].assignment == reservation.Assignment(name="name_value")
+
+
+@pytest.mark.asyncio
+async def test_create_assignment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_assignment(
+ reservation.CreateAssignmentRequest(),
+ parent="parent_value",
+ assignment=reservation.Assignment(name="name_value"),
+ )
+
+
+def test_list_assignments(
+ transport: str = "grpc", request_type=reservation.ListAssignmentsRequest
+):
+ client = ReservationServiceClient(
+ 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_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListAssignmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.list_assignments(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.ListAssignmentsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListAssignmentsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_assignments_from_dict():
+ test_list_assignments(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_list_assignments_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.ListAssignmentsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListAssignmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+
+ response = await client.list_assignments(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.ListAssignmentsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_assignments_field_headers():
+ client = ReservationServiceClient(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 = reservation.ListAssignmentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_assignments), "__call__"
+ ) as call:
+ call.return_value = reservation.ListAssignmentsResponse()
+
+ client.list_assignments(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_assignments_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.ListAssignmentsRequest()
+ 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_assignments), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListAssignmentsResponse()
+ )
+
+ await client.list_assignments(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_assignments_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListAssignmentsResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_assignments(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_assignments_flattened_error():
+ client = ReservationServiceClient(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_assignments(
+ reservation.ListAssignmentsRequest(), parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_assignments_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.ListAssignmentsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.ListAssignmentsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_assignments(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_assignments_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_assignments(
+ reservation.ListAssignmentsRequest(), parent="parent_value",
+ )
+
+
+def test_list_assignments_pager():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_assignments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListAssignmentsResponse(assignments=[], next_page_token="def",),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_assignments(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, reservation.Assignment) for i in results)
+
+
+def test_list_assignments_pages():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.list_assignments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListAssignmentsResponse(assignments=[], next_page_token="def",),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_assignments(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_assignments_async_pager():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_assignments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListAssignmentsResponse(assignments=[], next_page_token="def",),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_assignments(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, reservation.Assignment) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_assignments_async_pages():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.list_assignments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.ListAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.ListAssignmentsResponse(assignments=[], next_page_token="def",),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.ListAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.list_assignments(request={})).pages:
+ pages.append(page)
+ for page, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page.raw_page.next_page_token == token
+
+
+def test_delete_assignment(
+ transport: str = "grpc", request_type=reservation.DeleteAssignmentRequest
+):
+ client = ReservationServiceClient(
+ 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_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.delete_assignment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.DeleteAssignmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_assignment_from_dict():
+ test_delete_assignment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_delete_assignment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.DeleteAssignmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ response = await client.delete_assignment(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 response is None
+
+
+def test_delete_assignment_field_headers():
+ client = ReservationServiceClient(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 = reservation.DeleteAssignmentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_assignment), "__call__"
+ ) as call:
+ call.return_value = None
+
+ client.delete_assignment(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_assignment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.DeleteAssignmentRequest()
+ 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_assignment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ await client.delete_assignment(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_assignment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_assignment(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_assignment_flattened_error():
+ client = ReservationServiceClient(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_assignment(
+ reservation.DeleteAssignmentRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_assignment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_assignment(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_assignment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_assignment(
+ reservation.DeleteAssignmentRequest(), name="name_value",
+ )
+
+
+def test_search_assignments(
+ transport: str = "grpc", request_type=reservation.SearchAssignmentsRequest
+):
+ client = ReservationServiceClient(
+ 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.search_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.SearchAssignmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+
+ response = client.search_assignments(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.SearchAssignmentsRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.SearchAssignmentsPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_search_assignments_from_dict():
+ test_search_assignments(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_search_assignments_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.SearchAssignmentsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.search_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.SearchAssignmentsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+
+ response = await client.search_assignments(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.SearchAssignmentsAsyncPager)
+
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_search_assignments_field_headers():
+ client = ReservationServiceClient(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 = reservation.SearchAssignmentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.search_assignments), "__call__"
+ ) as call:
+ call.return_value = reservation.SearchAssignmentsResponse()
+
+ client.search_assignments(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_search_assignments_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.SearchAssignmentsRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.search_assignments), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.SearchAssignmentsResponse()
+ )
+
+ await client.search_assignments(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_search_assignments_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.search_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.SearchAssignmentsResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.search_assignments(
+ parent="parent_value", query="query_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].query == "query_value"
+
+
+def test_search_assignments_flattened_error():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.search_assignments(
+ reservation.SearchAssignmentsRequest(),
+ parent="parent_value",
+ query="query_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_search_assignments_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.search_assignments), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.SearchAssignmentsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.SearchAssignmentsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.search_assignments(
+ parent="parent_value", query="query_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].query == "query_value"
+
+
+@pytest.mark.asyncio
+async def test_search_assignments_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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.search_assignments(
+ reservation.SearchAssignmentsRequest(),
+ parent="parent_value",
+ query="query_value",
+ )
+
+
+def test_search_assignments_pager():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.search_assignments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.SearchAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[], next_page_token="def",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+
+ metadata = ()
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.search_assignments(request={})
+
+ assert pager._metadata == metadata
+
+ results = [i for i in pager]
+ assert len(results) == 6
+ assert all(isinstance(i, reservation.Assignment) for i in results)
+
+
+def test_search_assignments_pages():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials,)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.search_assignments), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.SearchAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[], next_page_token="def",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.search_assignments(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_search_assignments_async_pager():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.search_assignments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.SearchAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[], next_page_token="def",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.search_assignments(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, reservation.Assignment) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_search_assignments_async_pages():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials,
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.search_assignments),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ reservation.SearchAssignmentsResponse(
+ assignments=[
+ reservation.Assignment(),
+ reservation.Assignment(),
+ reservation.Assignment(),
+ ],
+ next_page_token="abc",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[], next_page_token="def",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(),], next_page_token="ghi",
+ ),
+ reservation.SearchAssignmentsResponse(
+ assignments=[reservation.Assignment(), reservation.Assignment(),],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page in (await client.search_assignments(request={})).pages:
+ pages.append(page)
+ for page, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page.raw_page.next_page_token == token
+
+
+def test_move_assignment(
+ transport: str = "grpc", request_type=reservation.MoveAssignmentRequest
+):
+ client = ReservationServiceClient(
+ 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.move_assignment), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Assignment(
+ name="name_value",
+ assignee="assignee_value",
+ job_type=reservation.Assignment.JobType.PIPELINE,
+ state=reservation.Assignment.State.PENDING,
+ )
+
+ response = client.move_assignment(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.MoveAssignmentRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.Assignment)
+
+ assert response.name == "name_value"
+
+ assert response.assignee == "assignee_value"
+
+ assert response.job_type == reservation.Assignment.JobType.PIPELINE
+
+ assert response.state == reservation.Assignment.State.PENDING
+
+
+def test_move_assignment_from_dict():
+ test_move_assignment(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_move_assignment_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.MoveAssignmentRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.move_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Assignment(
+ name="name_value",
+ assignee="assignee_value",
+ job_type=reservation.Assignment.JobType.PIPELINE,
+ state=reservation.Assignment.State.PENDING,
+ )
+ )
+
+ response = await client.move_assignment(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, reservation.Assignment)
+
+ assert response.name == "name_value"
+
+ assert response.assignee == "assignee_value"
+
+ assert response.job_type == reservation.Assignment.JobType.PIPELINE
+
+ assert response.state == reservation.Assignment.State.PENDING
+
+
+def test_move_assignment_field_headers():
+ client = ReservationServiceClient(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 = reservation.MoveAssignmentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.move_assignment), "__call__") as call:
+ call.return_value = reservation.Assignment()
+
+ client.move_assignment(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_move_assignment_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.MoveAssignmentRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.move_assignment), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Assignment()
+ )
+
+ await client.move_assignment(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_move_assignment_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client._transport.move_assignment), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Assignment()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.move_assignment(
+ name="name_value", destination_id="destination_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].name == "name_value"
+
+ assert args[0].destination_id == "destination_id_value"
+
+
+def test_move_assignment_flattened_error():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.move_assignment(
+ reservation.MoveAssignmentRequest(),
+ name="name_value",
+ destination_id="destination_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_move_assignment_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.move_assignment), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.Assignment()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.Assignment()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.move_assignment(
+ name="name_value", destination_id="destination_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].name == "name_value"
+
+ assert args[0].destination_id == "destination_id_value"
+
+
+@pytest.mark.asyncio
+async def test_move_assignment_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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.move_assignment(
+ reservation.MoveAssignmentRequest(),
+ name="name_value",
+ destination_id="destination_id_value",
+ )
+
+
+def test_get_bi_reservation(
+ transport: str = "grpc", request_type=reservation.GetBiReservationRequest
+):
+ client = ReservationServiceClient(
+ 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_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.BiReservation(name="name_value", size=443,)
+
+ response = client.get_bi_reservation(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.GetBiReservationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.BiReservation)
+
+ assert response.name == "name_value"
+
+ assert response.size == 443
+
+
+def test_get_bi_reservation_from_dict():
+ test_get_bi_reservation(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_get_bi_reservation_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.GetBiReservationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.BiReservation(name="name_value", size=443,)
+ )
+
+ response = await client.get_bi_reservation(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, reservation.BiReservation)
+
+ assert response.name == "name_value"
+
+ assert response.size == 443
+
+
+def test_get_bi_reservation_field_headers():
+ client = ReservationServiceClient(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 = reservation.GetBiReservationRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_bi_reservation), "__call__"
+ ) as call:
+ call.return_value = reservation.BiReservation()
+
+ client.get_bi_reservation(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_bi_reservation_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.GetBiReservationRequest()
+ 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_bi_reservation), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.BiReservation()
+ )
+
+ await client.get_bi_reservation(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_bi_reservation_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.BiReservation()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_bi_reservation(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_bi_reservation_flattened_error():
+ client = ReservationServiceClient(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_bi_reservation(
+ reservation.GetBiReservationRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_bi_reservation_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.BiReservation()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.BiReservation()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_bi_reservation(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_bi_reservation_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_bi_reservation(
+ reservation.GetBiReservationRequest(), name="name_value",
+ )
+
+
+def test_update_bi_reservation(
+ transport: str = "grpc", request_type=reservation.UpdateBiReservationRequest
+):
+ client = ReservationServiceClient(
+ 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_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.BiReservation(name="name_value", size=443,)
+
+ response = client.update_bi_reservation(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == reservation.UpdateBiReservationRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, reservation.BiReservation)
+
+ assert response.name == "name_value"
+
+ assert response.size == 443
+
+
+def test_update_bi_reservation_from_dict():
+ test_update_bi_reservation(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_update_bi_reservation_async(transport: str = "grpc_asyncio"):
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.UpdateBiReservationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.BiReservation(name="name_value", size=443,)
+ )
+
+ response = await client.update_bi_reservation(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, reservation.BiReservation)
+
+ assert response.name == "name_value"
+
+ assert response.size == 443
+
+
+def test_update_bi_reservation_field_headers():
+ client = ReservationServiceClient(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 = reservation.UpdateBiReservationRequest()
+ request.bi_reservation.name = "bi_reservation.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_bi_reservation), "__call__"
+ ) as call:
+ call.return_value = reservation.BiReservation()
+
+ client.update_bi_reservation(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",
+ "bi_reservation.name=bi_reservation.name/value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_bi_reservation_field_headers_async():
+ client = ReservationServiceAsyncClient(
+ 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 = reservation.UpdateBiReservationRequest()
+ request.bi_reservation.name = "bi_reservation.name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_bi_reservation), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.BiReservation()
+ )
+
+ await client.update_bi_reservation(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",
+ "bi_reservation.name=bi_reservation.name/value",
+ ) in kw["metadata"]
+
+
+def test_update_bi_reservation_flattened():
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.BiReservation()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_bi_reservation(
+ bi_reservation=reservation.BiReservation(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].bi_reservation == reservation.BiReservation(name="name_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_bi_reservation_flattened_error():
+ client = ReservationServiceClient(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_bi_reservation(
+ reservation.UpdateBiReservationRequest(),
+ bi_reservation=reservation.BiReservation(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_bi_reservation_flattened_async():
+ client = ReservationServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_bi_reservation), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = reservation.BiReservation()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ reservation.BiReservation()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_bi_reservation(
+ bi_reservation=reservation.BiReservation(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].bi_reservation == reservation.BiReservation(name="name_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_bi_reservation_flattened_error_async():
+ client = ReservationServiceAsyncClient(
+ 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_bi_reservation(
+ reservation.UpdateBiReservationRequest(),
+ bi_reservation=reservation.BiReservation(name="name_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.ReservationServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ReservationServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.ReservationServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ReservationServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.ReservationServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ReservationServiceClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ReservationServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = ReservationServiceClient(transport=transport)
+ assert client._transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ReservationServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.ReservationServiceGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = ReservationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client._transport, transports.ReservationServiceGrpcTransport,)
+
+
+def test_reservation_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.ReservationServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_reservation_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.bigquery.reservation_v1.services.reservation_service.transports.ReservationServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.ReservationServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "create_reservation",
+ "list_reservations",
+ "get_reservation",
+ "delete_reservation",
+ "update_reservation",
+ "create_capacity_commitment",
+ "list_capacity_commitments",
+ "get_capacity_commitment",
+ "delete_capacity_commitment",
+ "update_capacity_commitment",
+ "split_capacity_commitment",
+ "merge_capacity_commitments",
+ "create_assignment",
+ "list_assignments",
+ "delete_assignment",
+ "search_assignments",
+ "move_assignment",
+ "get_bi_reservation",
+ "update_bi_reservation",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+
+def test_reservation_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.bigquery.reservation_v1.services.reservation_service.transports.ReservationServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.ReservationServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/bigquery",
+ "https://www.googleapis.com/auth/cloud-platform",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_reservation_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)
+ ReservationServiceClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/bigquery",
+ "https://www.googleapis.com/auth/cloud-platform",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_reservation_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.ReservationServiceGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/bigquery",
+ "https://www.googleapis.com/auth/cloud-platform",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_reservation_service_host_no_port():
+ client = ReservationServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="bigqueryreservation.googleapis.com"
+ ),
+ )
+ assert client._transport._host == "bigqueryreservation.googleapis.com:443"
+
+
+def test_reservation_service_host_with_port():
+ client = ReservationServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="bigqueryreservation.googleapis.com:8000"
+ ),
+ )
+ assert client._transport._host == "bigqueryreservation.googleapis.com:8000"
+
+
+def test_reservation_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.ReservationServiceGrpcTransport(
+ 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_reservation_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.ReservationServiceGrpcAsyncIOTransport(
+ 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_reservation_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.ReservationServiceGrpcTransport(
+ 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/bigquery",
+ "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_reservation_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.ReservationServiceGrpcAsyncIOTransport(
+ 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/bigquery",
+ "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_reservation_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.ReservationServiceGrpcTransport(
+ 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/bigquery",
+ "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_reservation_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.ReservationServiceGrpcAsyncIOTransport(
+ 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/bigquery",
+ "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_assignment_path():
+ project = "squid"
+ location = "clam"
+ reservation = "whelk"
+ assignment = "octopus"
+
+ expected = "projects/{project}/locations/{location}/reservations/{reservation}/assignments/{assignment}".format(
+ project=project,
+ location=location,
+ reservation=reservation,
+ assignment=assignment,
+ )
+ actual = ReservationServiceClient.assignment_path(
+ project, location, reservation, assignment
+ )
+ assert expected == actual
+
+
+def test_parse_assignment_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ "reservation": "cuttlefish",
+ "assignment": "mussel",
+ }
+ path = ReservationServiceClient.assignment_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ReservationServiceClient.parse_assignment_path(path)
+ assert expected == actual
+
+
+def test_reservation_path():
+ project = "squid"
+ location = "clam"
+ reservation = "whelk"
+
+ expected = "projects/{project}/locations/{location}/reservations/{reservation}".format(
+ project=project, location=location, reservation=reservation,
+ )
+ actual = ReservationServiceClient.reservation_path(project, location, reservation)
+ assert expected == actual
+
+
+def test_parse_reservation_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "reservation": "nudibranch",
+ }
+ path = ReservationServiceClient.reservation_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ReservationServiceClient.parse_reservation_path(path)
+ assert expected == actual
+
+
+def test_bi_reservation_path():
+ project = "squid"
+ location = "clam"
+
+ expected = "projects/{project}/locations/{location}/bireservation".format(
+ project=project, location=location,
+ )
+ actual = ReservationServiceClient.bi_reservation_path(project, location)
+ assert expected == actual
+
+
+def test_parse_bi_reservation_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ }
+ path = ReservationServiceClient.bi_reservation_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ReservationServiceClient.parse_bi_reservation_path(path)
+ assert expected == actual
+
+
+def test_capacity_commitment_path():
+ project = "squid"
+ location = "clam"
+ capacity_commitment = "whelk"
+
+ expected = "projects/{project}/locations/{location}/capacityCommitments/{capacity_commitment}".format(
+ project=project, location=location, capacity_commitment=capacity_commitment,
+ )
+ actual = ReservationServiceClient.capacity_commitment_path(
+ project, location, capacity_commitment
+ )
+ assert expected == actual
+
+
+def test_parse_capacity_commitment_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "capacity_commitment": "nudibranch",
+ }
+ path = ReservationServiceClient.capacity_commitment_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ReservationServiceClient.parse_capacity_commitment_path(path)
+ assert expected == actual
diff --git a/tests/unit/reservation_v1/test_reservation_service.py b/tests/unit/reservation_v1/test_reservation_service.py
deleted file mode 100644
index 5829cd47..00000000
--- a/tests/unit/reservation_v1/test_reservation_service.py
+++ /dev/null
@@ -1,2183 +0,0 @@
-# -*- coding: utf-8 -*-
-
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from unittest import mock
-
-import grpc
-import math
-import pytest
-
-from google import auth
-from google.api_core import client_options
-from google.api_core import grpc_helpers
-from google.auth import credentials
-from google.cloud.bigquery.reservation_v1.services.reservation_service import (
- ReservationServiceClient,
-)
-from google.cloud.bigquery.reservation_v1.services.reservation_service import pagers
-from google.cloud.bigquery.reservation_v1.services.reservation_service import transports
-from google.cloud.bigquery.reservation_v1.types import reservation
-from google.cloud.bigquery.reservation_v1.types import reservation as gcbr_reservation
-from google.oauth2 import service_account
-from google.protobuf import any_pb2 as any # 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 google.rpc import status_pb2 as status # type: ignore
-
-
-def client_cert_source_callback():
- return b"cert bytes", b"key bytes"
-
-
-def test__get_default_mtls_endpoint():
- api_endpoint = "example.googleapis.com"
- api_mtls_endpoint = "example.mtls.googleapis.com"
- sandbox_endpoint = "example.sandbox.googleapis.com"
- sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
- non_googleapi = "api.example.com"
-
- assert ReservationServiceClient._get_default_mtls_endpoint(None) is None
- assert (
- ReservationServiceClient._get_default_mtls_endpoint(api_endpoint)
- == api_mtls_endpoint
- )
- assert (
- ReservationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
- == api_mtls_endpoint
- )
- assert (
- ReservationServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- ReservationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
- == sandbox_mtls_endpoint
- )
- assert (
- ReservationServiceClient._get_default_mtls_endpoint(non_googleapi)
- == non_googleapi
- )
-
-
-def test_reservation_service_client_from_service_account_file():
- creds = credentials.AnonymousCredentials()
- with mock.patch.object(
- service_account.Credentials, "from_service_account_file"
- ) as factory:
- factory.return_value = creds
- client = ReservationServiceClient.from_service_account_file(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- client = ReservationServiceClient.from_service_account_json(
- "dummy/file/path.json"
- )
- assert client._transport._credentials == creds
-
- assert client._transport._host == "bigqueryreservation.googleapis.com:443"
-
-
-def test_reservation_service_client_client_options():
- # Check that if channel is provided we won't create a new one.
- with mock.patch(
- "google.cloud.bigquery.reservation_v1.services.reservation_service.ReservationServiceClient.get_transport_class"
- ) as gtc:
- transport = transports.ReservationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = ReservationServiceClient(transport=transport)
- gtc.assert_not_called()
-
- # Check mTLS is not triggered with empty client options.
- options = client_options.ClientOptions()
- with mock.patch(
- "google.cloud.bigquery.reservation_v1.services.reservation_service.ReservationServiceClient.get_transport_class"
- ) as gtc:
- transport = gtc.return_value = mock.MagicMock()
- client = ReservationServiceClient(client_options=options)
- transport.assert_called_once_with(
- credentials=None, host=client.DEFAULT_ENDPOINT
- )
-
- # Check mTLS is not triggered if api_endpoint is provided but
- # client_cert_source is None.
- options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
- with mock.patch(
- "google.cloud.bigquery.reservation_v1.services.reservation_service.transports.ReservationServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = ReservationServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
- # Check mTLS is triggered if client_cert_source is provided.
- options = client_options.ClientOptions(
- client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.bigquery.reservation_v1.services.reservation_service.transports.ReservationServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = ReservationServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT,
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host=client.DEFAULT_ENDPOINT,
- )
-
- # Check mTLS is triggered if api_endpoint and client_cert_source are provided.
- options = client_options.ClientOptions(
- api_endpoint="squid.clam.whelk", client_cert_source=client_cert_source_callback
- )
- with mock.patch(
- "google.cloud.bigquery.reservation_v1.services.reservation_service.transports.ReservationServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = ReservationServiceClient(client_options=options)
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint="squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_reservation_service_client_client_options_from_dict():
- with mock.patch(
- "google.cloud.bigquery.reservation_v1.services.reservation_service.transports.ReservationServiceGrpcTransport.__init__"
- ) as grpc_transport:
- grpc_transport.return_value = None
- client = ReservationServiceClient(
- client_options={"api_endpoint": "squid.clam.whelk"}
- )
- grpc_transport.assert_called_once_with(
- api_mtls_endpoint=None,
- client_cert_source=None,
- credentials=None,
- host="squid.clam.whelk",
- )
-
-
-def test_create_reservation(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = gcbr_reservation.CreateReservationRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = gcbr_reservation.Reservation(
- name="name_value", slot_capacity=1391, ignore_idle_slots=True
- )
-
- response = client.create_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcbr_reservation.Reservation)
- assert response.name == "name_value"
- assert response.slot_capacity == 1391
-
- assert response.ignore_idle_slots is True
-
-
-def test_create_reservation_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = gcbr_reservation.Reservation()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.create_reservation(
- parent="parent_value",
- reservation=gcbr_reservation.Reservation(name="name_value"),
- reservation_id="reservation_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].reservation == gcbr_reservation.Reservation(name="name_value")
- assert args[0].reservation_id == "reservation_id_value"
-
-
-def test_create_reservation_flattened_error():
- client = ReservationServiceClient(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_reservation(
- gcbr_reservation.CreateReservationRequest(),
- parent="parent_value",
- reservation=gcbr_reservation.Reservation(name="name_value"),
- reservation_id="reservation_id_value",
- )
-
-
-def test_list_reservations(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.ListReservationsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_reservations), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.ListReservationsResponse(
- next_page_token="next_page_token_value"
- )
-
- response = client.list_reservations(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListReservationsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-def test_list_reservations_field_headers():
- client = ReservationServiceClient(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 = reservation.ListReservationsRequest(parent="parent/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_reservations), "__call__"
- ) as call:
- call.return_value = reservation.ListReservationsResponse()
- client.list_reservations(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
-
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
-
-
-def test_list_reservations_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_reservations), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.ListReservationsResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.list_reservations(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_reservations_flattened_error():
- client = ReservationServiceClient(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_reservations(
- reservation.ListReservationsRequest(), parent="parent_value"
- )
-
-
-def test_list_reservations_pager():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_reservations), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.ListReservationsResponse(
- reservations=[
- reservation.Reservation(),
- reservation.Reservation(),
- reservation.Reservation(),
- ],
- next_page_token="abc",
- ),
- reservation.ListReservationsResponse(
- reservations=[], next_page_token="def"
- ),
- reservation.ListReservationsResponse(
- reservations=[reservation.Reservation()], next_page_token="ghi"
- ),
- reservation.ListReservationsResponse(
- reservations=[reservation.Reservation(), reservation.Reservation()]
- ),
- RuntimeError,
- )
- results = [i for i in client.list_reservations(request={})]
- assert len(results) == 6
- assert all(isinstance(i, reservation.Reservation) for i in results)
-
-
-def test_list_reservations_pages():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_reservations), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.ListReservationsResponse(
- reservations=[
- reservation.Reservation(),
- reservation.Reservation(),
- reservation.Reservation(),
- ],
- next_page_token="abc",
- ),
- reservation.ListReservationsResponse(
- reservations=[], next_page_token="def"
- ),
- reservation.ListReservationsResponse(
- reservations=[reservation.Reservation()], next_page_token="ghi"
- ),
- reservation.ListReservationsResponse(
- reservations=[reservation.Reservation(), reservation.Reservation()]
- ),
- RuntimeError,
- )
- pages = list(client.list_reservations(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_get_reservation(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.GetReservationRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.get_reservation), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.Reservation(
- name="name_value", slot_capacity=1391, ignore_idle_slots=True
- )
-
- response = client.get_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.Reservation)
- assert response.name == "name_value"
- assert response.slot_capacity == 1391
-
- assert response.ignore_idle_slots is True
-
-
-def test_get_reservation_field_headers():
- client = ReservationServiceClient(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 = reservation.GetReservationRequest(name="name/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.get_reservation), "__call__") as call:
- call.return_value = reservation.Reservation()
- client.get_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
-
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
-
-
-def test_get_reservation_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.get_reservation), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.Reservation()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_reservation(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_reservation_flattened_error():
- client = ReservationServiceClient(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_reservation(reservation.GetReservationRequest(), name="name_value")
-
-
-def test_delete_reservation(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.DeleteReservationRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = None
-
- response = client.delete_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_delete_reservation_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = None
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.delete_reservation(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_reservation_flattened_error():
- client = ReservationServiceClient(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_reservation(
- reservation.DeleteReservationRequest(), name="name_value"
- )
-
-
-def test_update_reservation(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = gcbr_reservation.UpdateReservationRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = gcbr_reservation.Reservation(
- name="name_value", slot_capacity=1391, ignore_idle_slots=True
- )
-
- response = client.update_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, gcbr_reservation.Reservation)
- assert response.name == "name_value"
- assert response.slot_capacity == 1391
-
- assert response.ignore_idle_slots is True
-
-
-def test_update_reservation_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = gcbr_reservation.Reservation()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.update_reservation(
- reservation=gcbr_reservation.Reservation(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].reservation == gcbr_reservation.Reservation(name="name_value")
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
-
-
-def test_update_reservation_flattened_error():
- client = ReservationServiceClient(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_reservation(
- gcbr_reservation.UpdateReservationRequest(),
- reservation=gcbr_reservation.Reservation(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_create_capacity_commitment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.CreateCapacityCommitmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment(
- name="name_value",
- slot_count=1098,
- plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- state=reservation.CapacityCommitment.State.PENDING,
- renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- )
-
- response = client.create_capacity_commitment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.CapacityCommitment)
- assert response.name == "name_value"
- assert response.slot_count == 1098
- assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
- assert response.state == reservation.CapacityCommitment.State.PENDING
- assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
-
-
-def test_create_capacity_commitment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.create_capacity_commitment(
- parent="parent_value",
- capacity_commitment=reservation.CapacityCommitment(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].capacity_commitment == reservation.CapacityCommitment(
- name="name_value"
- )
-
-
-def test_create_capacity_commitment_flattened_error():
- client = ReservationServiceClient(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_capacity_commitment(
- reservation.CreateCapacityCommitmentRequest(),
- parent="parent_value",
- capacity_commitment=reservation.CapacityCommitment(name="name_value"),
- )
-
-
-def test_list_capacity_commitments(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.ListCapacityCommitmentsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_capacity_commitments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.ListCapacityCommitmentsResponse(
- next_page_token="next_page_token_value"
- )
-
- response = client.list_capacity_commitments(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListCapacityCommitmentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-def test_list_capacity_commitments_field_headers():
- client = ReservationServiceClient(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 = reservation.ListCapacityCommitmentsRequest(parent="parent/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_capacity_commitments), "__call__"
- ) as call:
- call.return_value = reservation.ListCapacityCommitmentsResponse()
- client.list_capacity_commitments(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
-
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
-
-
-def test_list_capacity_commitments_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_capacity_commitments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.ListCapacityCommitmentsResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.list_capacity_commitments(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_capacity_commitments_flattened_error():
- client = ReservationServiceClient(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_capacity_commitments(
- reservation.ListCapacityCommitmentsRequest(), parent="parent_value"
- )
-
-
-def test_list_capacity_commitments_pager():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_capacity_commitments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[
- reservation.CapacityCommitment(),
- reservation.CapacityCommitment(),
- reservation.CapacityCommitment(),
- ],
- next_page_token="abc",
- ),
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[], next_page_token="def"
- ),
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[reservation.CapacityCommitment()],
- next_page_token="ghi",
- ),
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[
- reservation.CapacityCommitment(),
- reservation.CapacityCommitment(),
- ]
- ),
- RuntimeError,
- )
- results = [i for i in client.list_capacity_commitments(request={})]
- assert len(results) == 6
- assert all(isinstance(i, reservation.CapacityCommitment) for i in results)
-
-
-def test_list_capacity_commitments_pages():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_capacity_commitments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[
- reservation.CapacityCommitment(),
- reservation.CapacityCommitment(),
- reservation.CapacityCommitment(),
- ],
- next_page_token="abc",
- ),
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[], next_page_token="def"
- ),
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[reservation.CapacityCommitment()],
- next_page_token="ghi",
- ),
- reservation.ListCapacityCommitmentsResponse(
- capacity_commitments=[
- reservation.CapacityCommitment(),
- reservation.CapacityCommitment(),
- ]
- ),
- RuntimeError,
- )
- pages = list(client.list_capacity_commitments(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_get_capacity_commitment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.GetCapacityCommitmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment(
- name="name_value",
- slot_count=1098,
- plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- state=reservation.CapacityCommitment.State.PENDING,
- renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- )
-
- response = client.get_capacity_commitment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.CapacityCommitment)
- assert response.name == "name_value"
- assert response.slot_count == 1098
- assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
- assert response.state == reservation.CapacityCommitment.State.PENDING
- assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
-
-
-def test_get_capacity_commitment_field_headers():
- client = ReservationServiceClient(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 = reservation.GetCapacityCommitmentRequest(name="name/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_capacity_commitment), "__call__"
- ) as call:
- call.return_value = reservation.CapacityCommitment()
- client.get_capacity_commitment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
-
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
-
-
-def test_get_capacity_commitment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_capacity_commitment(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_capacity_commitment_flattened_error():
- client = ReservationServiceClient(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_capacity_commitment(
- reservation.GetCapacityCommitmentRequest(), name="name_value"
- )
-
-
-def test_delete_capacity_commitment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.DeleteCapacityCommitmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = None
-
- response = client.delete_capacity_commitment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_delete_capacity_commitment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = None
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.delete_capacity_commitment(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_capacity_commitment_flattened_error():
- client = ReservationServiceClient(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_capacity_commitment(
- reservation.DeleteCapacityCommitmentRequest(), name="name_value"
- )
-
-
-def test_update_capacity_commitment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.UpdateCapacityCommitmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment(
- name="name_value",
- slot_count=1098,
- plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- state=reservation.CapacityCommitment.State.PENDING,
- renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- )
-
- response = client.update_capacity_commitment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.CapacityCommitment)
- assert response.name == "name_value"
- assert response.slot_count == 1098
- assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
- assert response.state == reservation.CapacityCommitment.State.PENDING
- assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
-
-
-def test_update_capacity_commitment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.update_capacity_commitment(
- capacity_commitment=reservation.CapacityCommitment(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].capacity_commitment == reservation.CapacityCommitment(
- name="name_value"
- )
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
-
-
-def test_update_capacity_commitment_flattened_error():
- client = ReservationServiceClient(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_capacity_commitment(
- reservation.UpdateCapacityCommitmentRequest(),
- capacity_commitment=reservation.CapacityCommitment(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_split_capacity_commitment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.SplitCapacityCommitmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.split_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.SplitCapacityCommitmentResponse()
-
- response = client.split_capacity_commitment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.SplitCapacityCommitmentResponse)
-
-
-def test_split_capacity_commitment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.split_capacity_commitment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.SplitCapacityCommitmentResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.split_capacity_commitment(name="name_value", slot_count=1098)
-
- # Establish that the underlying call was made with the expected
- # request object values.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0].name == "name_value"
- assert args[0].slot_count == 1098
-
-
-def test_split_capacity_commitment_flattened_error():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.split_capacity_commitment(
- reservation.SplitCapacityCommitmentRequest(),
- name="name_value",
- slot_count=1098,
- )
-
-
-def test_merge_capacity_commitments(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.MergeCapacityCommitmentsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.merge_capacity_commitments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment(
- name="name_value",
- slot_count=1098,
- plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- state=reservation.CapacityCommitment.State.PENDING,
- renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX,
- )
-
- response = client.merge_capacity_commitments(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.CapacityCommitment)
- assert response.name == "name_value"
- assert response.slot_count == 1098
- assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
- assert response.state == reservation.CapacityCommitment.State.PENDING
- assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX
-
-
-def test_merge_capacity_commitments_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.merge_capacity_commitments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.CapacityCommitment()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.merge_capacity_commitments(
- parent="parent_value",
- capacity_commitment_ids=["capacity_commitment_ids_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].capacity_commitment_ids == ["capacity_commitment_ids_value"]
-
-
-def test_merge_capacity_commitments_flattened_error():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.merge_capacity_commitments(
- reservation.MergeCapacityCommitmentsRequest(),
- parent="parent_value",
- capacity_commitment_ids=["capacity_commitment_ids_value"],
- )
-
-
-def test_create_assignment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.CreateAssignmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_assignment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.Assignment(
- name="name_value",
- assignee="assignee_value",
- job_type=reservation.Assignment.JobType.PIPELINE,
- state=reservation.Assignment.State.PENDING,
- )
-
- response = client.create_assignment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.Assignment)
- assert response.name == "name_value"
- assert response.assignee == "assignee_value"
- assert response.job_type == reservation.Assignment.JobType.PIPELINE
- assert response.state == reservation.Assignment.State.PENDING
-
-
-def test_create_assignment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.create_assignment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.Assignment()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.create_assignment(
- parent="parent_value", assignment=reservation.Assignment(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].assignment == reservation.Assignment(name="name_value")
-
-
-def test_create_assignment_flattened_error():
- client = ReservationServiceClient(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_assignment(
- reservation.CreateAssignmentRequest(),
- parent="parent_value",
- assignment=reservation.Assignment(name="name_value"),
- )
-
-
-def test_list_assignments(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.ListAssignmentsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_assignments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.ListAssignmentsResponse(
- next_page_token="next_page_token_value"
- )
-
- response = client.list_assignments(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListAssignmentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-def test_list_assignments_field_headers():
- client = ReservationServiceClient(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 = reservation.ListAssignmentsRequest(parent="parent/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_assignments), "__call__"
- ) as call:
- call.return_value = reservation.ListAssignmentsResponse()
- client.list_assignments(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
-
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
-
-
-def test_list_assignments_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_assignments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.ListAssignmentsResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.list_assignments(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_assignments_flattened_error():
- client = ReservationServiceClient(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_assignments(
- reservation.ListAssignmentsRequest(), parent="parent_value"
- )
-
-
-def test_list_assignments_pager():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_assignments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.ListAssignmentsResponse(
- assignments=[
- reservation.Assignment(),
- reservation.Assignment(),
- reservation.Assignment(),
- ],
- next_page_token="abc",
- ),
- reservation.ListAssignmentsResponse(assignments=[], next_page_token="def"),
- reservation.ListAssignmentsResponse(
- assignments=[reservation.Assignment()], next_page_token="ghi"
- ),
- reservation.ListAssignmentsResponse(
- assignments=[reservation.Assignment(), reservation.Assignment()]
- ),
- RuntimeError,
- )
- results = [i for i in client.list_assignments(request={})]
- assert len(results) == 6
- assert all(isinstance(i, reservation.Assignment) for i in results)
-
-
-def test_list_assignments_pages():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.list_assignments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.ListAssignmentsResponse(
- assignments=[
- reservation.Assignment(),
- reservation.Assignment(),
- reservation.Assignment(),
- ],
- next_page_token="abc",
- ),
- reservation.ListAssignmentsResponse(assignments=[], next_page_token="def"),
- reservation.ListAssignmentsResponse(
- assignments=[reservation.Assignment()], next_page_token="ghi"
- ),
- reservation.ListAssignmentsResponse(
- assignments=[reservation.Assignment(), reservation.Assignment()]
- ),
- RuntimeError,
- )
- pages = list(client.list_assignments(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_delete_assignment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.DeleteAssignmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_assignment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = None
-
- response = client.delete_assignment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert response is None
-
-
-def test_delete_assignment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.delete_assignment), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = None
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.delete_assignment(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_assignment_flattened_error():
- client = ReservationServiceClient(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_assignment(
- reservation.DeleteAssignmentRequest(), name="name_value"
- )
-
-
-def test_search_assignments(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.SearchAssignmentsRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.search_assignments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.SearchAssignmentsResponse(
- next_page_token="next_page_token_value"
- )
-
- response = client.search_assignments(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, pagers.SearchAssignmentsPager)
- assert response.next_page_token == "next_page_token_value"
-
-
-def test_search_assignments_field_headers():
- client = ReservationServiceClient(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 = reservation.SearchAssignmentsRequest(parent="parent/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.search_assignments), "__call__"
- ) as call:
- call.return_value = reservation.SearchAssignmentsResponse()
- client.search_assignments(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
-
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"]
-
-
-def test_search_assignments_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.search_assignments), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.SearchAssignmentsResponse()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.search_assignments(parent="parent_value", query="query_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].query == "query_value"
-
-
-def test_search_assignments_flattened_error():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.search_assignments(
- reservation.SearchAssignmentsRequest(),
- parent="parent_value",
- query="query_value",
- )
-
-
-def test_search_assignments_pager():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.search_assignments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.SearchAssignmentsResponse(
- assignments=[
- reservation.Assignment(),
- reservation.Assignment(),
- reservation.Assignment(),
- ],
- next_page_token="abc",
- ),
- reservation.SearchAssignmentsResponse(
- assignments=[], next_page_token="def"
- ),
- reservation.SearchAssignmentsResponse(
- assignments=[reservation.Assignment()], next_page_token="ghi"
- ),
- reservation.SearchAssignmentsResponse(
- assignments=[reservation.Assignment(), reservation.Assignment()]
- ),
- RuntimeError,
- )
- results = [i for i in client.search_assignments(request={})]
- assert len(results) == 6
- assert all(isinstance(i, reservation.Assignment) for i in results)
-
-
-def test_search_assignments_pages():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials)
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.search_assignments), "__call__"
- ) as call:
- # Set the response to a series of pages.
- call.side_effect = (
- reservation.SearchAssignmentsResponse(
- assignments=[
- reservation.Assignment(),
- reservation.Assignment(),
- reservation.Assignment(),
- ],
- next_page_token="abc",
- ),
- reservation.SearchAssignmentsResponse(
- assignments=[], next_page_token="def"
- ),
- reservation.SearchAssignmentsResponse(
- assignments=[reservation.Assignment()], next_page_token="ghi"
- ),
- reservation.SearchAssignmentsResponse(
- assignments=[reservation.Assignment(), reservation.Assignment()]
- ),
- RuntimeError,
- )
- pages = list(client.search_assignments(request={}).pages)
- for page, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page.raw_page.next_page_token == token
-
-
-def test_move_assignment(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.MoveAssignmentRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.move_assignment), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.Assignment(
- name="name_value",
- assignee="assignee_value",
- job_type=reservation.Assignment.JobType.PIPELINE,
- state=reservation.Assignment.State.PENDING,
- )
-
- response = client.move_assignment(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.Assignment)
- assert response.name == "name_value"
- assert response.assignee == "assignee_value"
- assert response.job_type == reservation.Assignment.JobType.PIPELINE
- assert response.state == reservation.Assignment.State.PENDING
-
-
-def test_move_assignment_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(type(client._transport.move_assignment), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.Assignment()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.move_assignment(
- name="name_value", destination_id="destination_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].name == "name_value"
- assert args[0].destination_id == "destination_id_value"
-
-
-def test_move_assignment_flattened_error():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Attempting to call a method with both a request object and flattened
- # fields is an error.
- with pytest.raises(ValueError):
- client.move_assignment(
- reservation.MoveAssignmentRequest(),
- name="name_value",
- destination_id="destination_id_value",
- )
-
-
-def test_get_bi_reservation(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.GetBiReservationRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_bi_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.BiReservation(name="name_value", size=443)
-
- response = client.get_bi_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.BiReservation)
- assert response.name == "name_value"
- assert response.size == 443
-
-
-def test_get_bi_reservation_field_headers():
- client = ReservationServiceClient(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 = reservation.GetBiReservationRequest(name="name/value")
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_bi_reservation), "__call__"
- ) as call:
- call.return_value = reservation.BiReservation()
- client.get_bi_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
- assert args[0] == request
-
- # Establish that the field header was sent.
- _, _, kw = call.mock_calls[0]
- assert ("x-goog-request-params", "name=name/value") in kw["metadata"]
-
-
-def test_get_bi_reservation_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.get_bi_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.BiReservation()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.get_bi_reservation(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_bi_reservation_flattened_error():
- client = ReservationServiceClient(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_bi_reservation(
- reservation.GetBiReservationRequest(), name="name_value"
- )
-
-
-def test_update_bi_reservation(transport: str = "grpc"):
- client = ReservationServiceClient(
- 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 = reservation.UpdateBiReservationRequest()
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_bi_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.BiReservation(name="name_value", size=443)
-
- response = client.update_bi_reservation(request)
-
- # Establish that the underlying gRPC stub method was called.
- assert len(call.mock_calls) == 1
- _, args, _ = call.mock_calls[0]
-
- assert args[0] == request
-
- # Establish that the response is the type that we expect.
- assert isinstance(response, reservation.BiReservation)
- assert response.name == "name_value"
- assert response.size == 443
-
-
-def test_update_bi_reservation_flattened():
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
-
- # Mock the actual call within the gRPC stub, and fake the request.
- with mock.patch.object(
- type(client._transport.update_bi_reservation), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = reservation.BiReservation()
-
- # Call the method with a truthy value for each flattened field,
- # using the keyword arguments to the method.
- response = client.update_bi_reservation(
- bi_reservation=reservation.BiReservation(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].bi_reservation == reservation.BiReservation(name="name_value")
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
-
-
-def test_update_bi_reservation_flattened_error():
- client = ReservationServiceClient(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_bi_reservation(
- reservation.UpdateBiReservationRequest(),
- bi_reservation=reservation.BiReservation(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
- )
-
-
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.ReservationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- with pytest.raises(ValueError):
- client = ReservationServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport
- )
-
-
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ReservationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials()
- )
- client = ReservationServiceClient(transport=transport)
- assert client._transport is transport
-
-
-def test_transport_grpc_default():
- # A client should use the gRPC transport by default.
- client = ReservationServiceClient(credentials=credentials.AnonymousCredentials())
- assert isinstance(client._transport, transports.ReservationServiceGrpcTransport)
-
-
-def test_reservation_service_base_transport():
- # Instantiate the base transport.
- transport = transports.ReservationServiceTransport(
- credentials=credentials.AnonymousCredentials()
- )
-
- # Every method on the transport should just blindly
- # raise NotImplementedError.
- methods = (
- "create_reservation",
- "list_reservations",
- "get_reservation",
- "delete_reservation",
- "update_reservation",
- "create_capacity_commitment",
- "list_capacity_commitments",
- "get_capacity_commitment",
- "delete_capacity_commitment",
- "update_capacity_commitment",
- "split_capacity_commitment",
- "merge_capacity_commitments",
- "create_assignment",
- "list_assignments",
- "delete_assignment",
- "search_assignments",
- "move_assignment",
- "get_bi_reservation",
- "update_bi_reservation",
- )
- for method in methods:
- with pytest.raises(NotImplementedError):
- getattr(transport, method)(request=object())
-
-
-def test_reservation_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)
- ReservationServiceClient()
- adc.assert_called_once_with(
- scopes=(
- "https://www.googleapis.com/auth/bigquery",
- "https://www.googleapis.com/auth/cloud-platform",
- )
- )
-
-
-def test_reservation_service_host_no_port():
- client = ReservationServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="bigqueryreservation.googleapis.com"
- ),
- transport="grpc",
- )
- assert client._transport._host == "bigqueryreservation.googleapis.com:443"
-
-
-def test_reservation_service_host_with_port():
- client = ReservationServiceClient(
- credentials=credentials.AnonymousCredentials(),
- client_options=client_options.ClientOptions(
- api_endpoint="bigqueryreservation.googleapis.com:8000"
- ),
- transport="grpc",
- )
- assert client._transport._host == "bigqueryreservation.googleapis.com:8000"
-
-
-def test_reservation_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.ReservationServiceGrpcTransport(
- 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_reservation_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.ReservationServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint="mtls.squid.clam.whelk",
- client_cert_source=client_cert_source_callback,
- )
- grpc_ssl_channel_cred.assert_called_once_with(
- certificate_chain=b"cert bytes", private_key=b"key bytes"
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=(
- "https://www.googleapis.com/auth/bigquery",
- "https://www.googleapis.com/auth/cloud-platform",
- ),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-@pytest.mark.parametrize(
- "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"]
-)
-@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True)
-def test_reservation_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.ReservationServiceGrpcTransport(
- host="squid.clam.whelk",
- credentials=mock_cred,
- api_mtls_endpoint=api_mtls_endpoint,
- client_cert_source=None,
- )
- grpc_create_channel.assert_called_once_with(
- "mtls.squid.clam.whelk:443",
- credentials=mock_cred,
- ssl_credentials=mock_ssl_cred,
- scopes=(
- "https://www.googleapis.com/auth/bigquery",
- "https://www.googleapis.com/auth/cloud-platform",
- ),
- )
- assert transport.grpc_channel == mock_grpc_channel
-
-
-def test_capacity_commitment_path():
- project = "squid"
- location = "clam"
- capacity_commitment = "whelk"
-
- expected = "projects/{project}/locations/{location}/capacityCommitments/{capacity_commitment}".format(
- project=project, location=location, capacity_commitment=capacity_commitment
- )
- actual = ReservationServiceClient.capacity_commitment_path(
- project, location, capacity_commitment
- )
- assert expected == actual
-
-
-def test_parse_capacity_commitment_path():
- expected = {
- "project": "octopus",
- "location": "oyster",
- "capacity_commitment": "nudibranch",
- }
- path = ReservationServiceClient.capacity_commitment_path(**expected)
-
- # Check that the path construction is reversible.
- actual = ReservationServiceClient.parse_capacity_commitment_path(path)
- assert expected == actual
-
-
-def test_reservation_path():
- project = "squid"
- location = "clam"
- reservation = "whelk"
-
- expected = "projects/{project}/locations/{location}/reservations/{reservation}".format(
- project=project, location=location, reservation=reservation
- )
- actual = ReservationServiceClient.reservation_path(project, location, reservation)
- assert expected == actual
-
-
-def test_parse_reservation_path():
- expected = {"project": "octopus", "location": "oyster", "reservation": "nudibranch"}
- path = ReservationServiceClient.reservation_path(**expected)
-
- # Check that the path construction is reversible.
- actual = ReservationServiceClient.parse_reservation_path(path)
- assert expected == actual
-
-
-def test_bi_reservation_path():
- project = "squid"
- location = "clam"
-
- expected = "projects/{project}/locations/{location}/bireservation".format(
- project=project, location=location
- )
- actual = ReservationServiceClient.bi_reservation_path(project, location)
- assert expected == actual
-
-
-def test_parse_bi_reservation_path():
- expected = {"project": "whelk", "location": "octopus"}
- path = ReservationServiceClient.bi_reservation_path(**expected)
-
- # Check that the path construction is reversible.
- actual = ReservationServiceClient.parse_bi_reservation_path(path)
- assert expected == actual
-
-
-def test_assignment_path():
- project = "squid"
- location = "clam"
- reservation = "whelk"
- assignment = "octopus"
-
- expected = "projects/{project}/locations/{location}/reservations/{reservation}/assignments/{assignment}".format(
- project=project,
- location=location,
- reservation=reservation,
- assignment=assignment,
- )
- actual = ReservationServiceClient.assignment_path(
- project, location, reservation, assignment
- )
- assert expected == actual
-
-
-def test_parse_assignment_path():
- expected = {
- "project": "oyster",
- "location": "nudibranch",
- "reservation": "cuttlefish",
- "assignment": "mussel",
- }
- path = ReservationServiceClient.assignment_path(**expected)
-
- # Check that the path construction is reversible.
- actual = ReservationServiceClient.parse_assignment_path(path)
- assert expected == actual