diff --git a/.coveragerc b/.coveragerc
index dd39c854..4ad22152 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -1,35 +1,17 @@
-# -*- 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
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Generated by synthtool. DO NOT EDIT!
[run]
branch = True
[report]
-fail_under = 100
show_missing = True
+omit =
+ google/cloud/talent/__init__.py
exclude_lines =
# Re-enable the standard pragma
pragma: NO COVER
# Ignore debug-only repr
def __repr__
- # Ignore abstract methods
- raise NotImplementedError
-omit =
- */gapic/*.py
- */proto/*.py
- */core/*.py
- */site-packages/*.py
\ No newline at end of file
+ # Ignore pkg_resources exceptions.
+ # This is added at the module level as a safeguard for if someone
+ # generates the code and tries to run it without pip installing. This
+ # makes it virtually impossible to test properly.
+ except pkg_resources.DistributionNotFound
diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml
new file mode 100644
index 00000000..e2b39f94
--- /dev/null
+++ b/.github/.OwlBot.lock.yaml
@@ -0,0 +1,3 @@
+docker:
+ image: gcr.io/repo-automation-bots/owlbot-python:latest
+ digest: sha256:99d90d097e4a4710cc8658ee0b5b963f4426d0e424819787c3ac1405c9a26719
diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml
new file mode 100644
index 00000000..4fea0dda
--- /dev/null
+++ b/.github/.OwlBot.yaml
@@ -0,0 +1,26 @@
+# Copyright 2021 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.
+
+docker:
+ image: gcr.io/repo-automation-bots/owlbot-python:latest
+
+deep-remove-regex:
+ - /owl-bot-staging
+
+deep-copy-regex:
+ - source: /google/cloud/talent/(v.*)/.*-py/(.*)
+ dest: /owl-bot-staging/$1/$2
+
+begin-after-commit-hash: 15a0e742d765a1c7afcf41b9e1554f8b03b578fc
+
diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml
new file mode 100644
index 00000000..6fe78aa7
--- /dev/null
+++ b/.github/header-checker-lint.yml
@@ -0,0 +1,15 @@
+{"allowedCopyrightHolders": ["Google LLC"],
+ "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"],
+ "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"],
+ "sourceFileExtensions": [
+ "ts",
+ "js",
+ "java",
+ "sh",
+ "Dockerfile",
+ "yaml",
+ "py",
+ "html",
+ "txt"
+ ]
+}
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index b9daa52f..b4243ced 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,8 +50,10 @@ docs.metadata
# Virtual environment
env/
+
+# Test logs
coverage.xml
-sponge_log.xml
+*sponge_log.xml
# System test environment variables.
system_tests/local_test_setup
diff --git a/.kokoro/build.sh b/.kokoro/build.sh
index 291a09e9..6e491f98 100755
--- a/.kokoro/build.sh
+++ b/.kokoro/build.sh
@@ -15,7 +15,11 @@
set -eo pipefail
-cd github/python-talent
+if [[ -z "${PROJECT_ROOT:-}" ]]; then
+ PROJECT_ROOT="github/python-talent"
+fi
+
+cd "${PROJECT_ROOT}"
# Disable buffering, so that the logs stream through.
export PYTHONUNBUFFERED=1
@@ -30,16 +34,26 @@ export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/service-account.json
export PROJECT_ID=$(cat "${KOKORO_GFILE_DIR}/project-id.json")
# Remove old nox
-python3.6 -m pip uninstall --yes --quiet nox-automation
+python3 -m pip uninstall --yes --quiet nox-automation
# Install nox
-python3.6 -m pip install --upgrade --quiet nox
-python3.6 -m nox --version
+python3 -m pip install --upgrade --quiet nox
+python3 -m nox --version
+
+# If this is a continuous build, send the test log to the FlakyBot.
+# See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot.
+if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]]; then
+ cleanup() {
+ chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot
+ $KOKORO_GFILE_DIR/linux_amd64/flakybot
+ }
+ trap cleanup EXIT HUP
+fi
# 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:-}"
+ python3 -m nox -s ${NOX_SESSION:-}
else
- python3.6 -m nox
+ python3 -m nox
fi
diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg
index 11181078..d5bb31d6 100644
--- a/.kokoro/docs/docs-presubmit.cfg
+++ b/.kokoro/docs/docs-presubmit.cfg
@@ -15,3 +15,14 @@ env_vars: {
key: "TRAMPOLINE_IMAGE_UPLOAD"
value: "false"
}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-talent/.kokoro/build.sh"
+}
+
+# Only run this nox session.
+env_vars: {
+ key: "NOX_SESSION"
+ value: "docs docfx"
+}
diff --git a/.kokoro/release.sh b/.kokoro/release.sh
index af8391be..7859f7d9 100755
--- a/.kokoro/release.sh
+++ b/.kokoro/release.sh
@@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools
export PYTHONUNBUFFERED=1
# Move into the package, build the distribution and upload.
-TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google_cloud_pypi_password")
+TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token")
cd github/python-talent
python3 setup.py sdist bdist_wheel
-twine upload --username gcloudpypi --password "${TWINE_PASSWORD}" dist/*
+twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/*
diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg
index 5dd54678..c83b4a17 100644
--- a/.kokoro/release/common.cfg
+++ b/.kokoro/release/common.cfg
@@ -23,18 +23,8 @@ env_vars: {
value: "github/python-talent/.kokoro/release.sh"
}
-# Fetch PyPI password
-before_action {
- fetch_keystore {
- keystore_resource {
- keystore_config_id: 73713
- keyname: "google_cloud_pypi_password"
- }
- }
-}
-
# Tokens needed to report release status back to GitHub
env_vars: {
key: "SECRET_MANAGER_KEYS"
- value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem"
-}
\ No newline at end of file
+ value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token"
+}
diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg
new file mode 100644
index 00000000..f9cfcd33
--- /dev/null
+++ b/.kokoro/samples/python3.6/periodic-head.cfg
@@ -0,0 +1,11 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-pubsub/.kokoro/test-samples-against-head.sh"
+}
diff --git a/.kokoro/samples/python3.7/periodic-head.cfg b/.kokoro/samples/python3.7/periodic-head.cfg
new file mode 100644
index 00000000..f9cfcd33
--- /dev/null
+++ b/.kokoro/samples/python3.7/periodic-head.cfg
@@ -0,0 +1,11 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-pubsub/.kokoro/test-samples-against-head.sh"
+}
diff --git a/.kokoro/samples/python3.8/periodic-head.cfg b/.kokoro/samples/python3.8/periodic-head.cfg
new file mode 100644
index 00000000..f9cfcd33
--- /dev/null
+++ b/.kokoro/samples/python3.8/periodic-head.cfg
@@ -0,0 +1,11 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-pubsub/.kokoro/test-samples-against-head.sh"
+}
diff --git a/.kokoro/samples/python3.9/common.cfg b/.kokoro/samples/python3.9/common.cfg
new file mode 100644
index 00000000..f7f6cd8c
--- /dev/null
+++ b/.kokoro/samples/python3.9/common.cfg
@@ -0,0 +1,40 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+# Build logs will be here
+action {
+ define_artifacts {
+ regex: "**/*sponge_log.xml"
+ }
+}
+
+# Specify which tests to run
+env_vars: {
+ key: "RUN_TESTS_SESSION"
+ value: "py-3.9"
+}
+
+# Declare build specific Cloud project.
+env_vars: {
+ key: "BUILD_SPECIFIC_GCLOUD_PROJECT"
+ value: "python-docs-samples-tests-py39"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-talent/.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-talent/.kokoro/trampoline.sh"
\ No newline at end of file
diff --git a/.kokoro/samples/python3.9/continuous.cfg b/.kokoro/samples/python3.9/continuous.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.9/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.9/periodic-head.cfg b/.kokoro/samples/python3.9/periodic-head.cfg
new file mode 100644
index 00000000..f9cfcd33
--- /dev/null
+++ b/.kokoro/samples/python3.9/periodic-head.cfg
@@ -0,0 +1,11 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "INSTALL_LIBRARY_FROM_SOURCE"
+ value: "True"
+}
+
+env_vars: {
+ key: "TRAMPOLINE_BUILD_FILE"
+ value: "github/python-pubsub/.kokoro/test-samples-against-head.sh"
+}
diff --git a/.kokoro/samples/python3.9/periodic.cfg b/.kokoro/samples/python3.9/periodic.cfg
new file mode 100644
index 00000000..50fec964
--- /dev/null
+++ b/.kokoro/samples/python3.9/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.9/presubmit.cfg b/.kokoro/samples/python3.9/presubmit.cfg
new file mode 100644
index 00000000..a1c8d975
--- /dev/null
+++ b/.kokoro/samples/python3.9/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-against-head.sh b/.kokoro/test-samples-against-head.sh
new file mode 100755
index 00000000..ecd01578
--- /dev/null
+++ b/.kokoro/test-samples-against-head.sh
@@ -0,0 +1,28 @@
+#!/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.
+
+# A customized test runner for samples.
+#
+# For periodic builds, you can specify this file for testing against head.
+
+# `-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-talent
+
+exec .kokoro/test-samples-impl.sh
diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh
new file mode 100755
index 00000000..cf5de74c
--- /dev/null
+++ b/.kokoro/test-samples-impl.sh
@@ -0,0 +1,102 @@
+#!/bin/bash
+# Copyright 2021 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
+
+# Exit early if samples directory doesn't exist
+if [ ! -d "./samples" ]; then
+ echo "No tests run. `./samples` not found"
+ exit 0
+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 FlakyBot.
+ # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot.
+ if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then
+ chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot
+ $KOKORO_GFILE_DIR/linux_amd64/flakybot
+ 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"
diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh
index 71fab05d..09ba8e25 100755
--- a/.kokoro/test-samples.sh
+++ b/.kokoro/test-samples.sh
@@ -13,6 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+# The default test runner for samples.
+#
+# For periodic builds, we rewinds the repo to the latest release, and
+# run test-samples-impl.sh.
# `-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
@@ -24,87 +28,19 @@ cd github/python-talent
# Run periodic samples tests at latest release
if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then
+ # preserving the test runner implementation.
+ cp .kokoro/test-samples-impl.sh "${TMPDIR}/test-samples-impl.sh"
+ echo "--- IMPORTANT IMPORTANT IMPORTANT ---"
+ echo "Now we rewind the repo back to the latest release..."
LATEST_RELEASE=$(git describe --abbrev=0 --tags)
git checkout $LATEST_RELEASE
-fi
-
-# Exit early if samples directory doesn't exist
-if [ ! -d "./samples" ]; then
- echo "No tests run. `./samples` not found"
- exit 0
-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 FlakyBot.
- # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot.
- if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then
- chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot
- $KOKORO_GFILE_DIR/linux_amd64/flakybot
+ echo "The current head is: "
+ echo $(git rev-parse --verify HEAD)
+ echo "--- IMPORTANT IMPORTANT IMPORTANT ---"
+ # move back the test runner implementation if there's no file.
+ if [ ! -f .kokoro/test-samples-impl.sh ]; then
+ cp "${TMPDIR}/test-samples-impl.sh" .kokoro/test-samples-impl.sh
fi
+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"
+exec .kokoro/test-samples-impl.sh
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index a9024b15..62eb5a77 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,8 +1,22 @@
+# Copyright 2021 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.
+#
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v3.4.0
+ rev: v4.0.1
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
@@ -12,6 +26,6 @@ repos:
hooks:
- id: black
- repo: https://gitlab.com/pycqa/flake8
- rev: 3.8.4
+ rev: 3.9.2
hooks:
- id: flake8
diff --git a/.repo-metadata.json b/.repo-metadata.json
index 04e3ec1b..da5fbbbf 100644
--- a/.repo-metadata.json
+++ b/.repo-metadata.json
@@ -6,6 +6,7 @@
"issue_tracker": "https://issuetracker.google.com/savedsearches/559664",
"release_level": "beta",
"language": "python",
+ "library_type": "GAPIC_AUTO",
"repo": "googleapis/python-talent",
"distribution_name": "google-cloud-talent",
"api_id": "jobs.googleapis.com",
diff --git a/.trampolinerc b/.trampolinerc
index 995ee291..383b6ec8 100644
--- a/.trampolinerc
+++ b/.trampolinerc
@@ -24,6 +24,7 @@ required_envvars+=(
pass_down_envvars+=(
"STAGING_BUCKET"
"V2_STAGING_BUCKET"
+ "NOX_SESSION"
)
# Prevent unintentional override on the default image.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d2981ef..f11ecb1f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,27 @@
[1]: https://pypi.org/project/google-cloud-talent/#history
+## [2.2.0](https://www.github.com/googleapis/python-talent/compare/v2.1.0...v2.2.0) (2021-06-30)
+
+
+### Features
+
+* add `from_service_account_info` ([095747e](https://www.github.com/googleapis/python-talent/commit/095747e8b517769a9caa2df6babf96fd526d0a22))
+* add always_use_jwt_access ([#112](https://www.github.com/googleapis/python-talent/issues/112)) ([01c8095](https://www.github.com/googleapis/python-talent/commit/01c8095182503fa8d7ca593f4701f87fe00621ff))
+
+
+### Bug Fixes
+
+* **deps:** add packaging requirement ([#99](https://www.github.com/googleapis/python-talent/issues/99)) ([c00ab57](https://www.github.com/googleapis/python-talent/commit/c00ab5750a4062b7de24fcba5798171be174f131))
+* disable always_use_jwt_access ([a422ac0](https://www.github.com/googleapis/python-talent/commit/a422ac00d270bef6f66d6d29b674505c3a152e33))
+* disable always_use_jwt_access ([#115](https://www.github.com/googleapis/python-talent/issues/115)) ([a422ac0](https://www.github.com/googleapis/python-talent/commit/a422ac00d270bef6f66d6d29b674505c3a152e33))
+* fix retry deadlines ([#73](https://www.github.com/googleapis/python-talent/issues/73)) ([095747e](https://www.github.com/googleapis/python-talent/commit/095747e8b517769a9caa2df6babf96fd526d0a22))
+
+
+### Documentation
+
+* omit mention of Python 2.7 in 'CONTRIBUTING.rst' ([#1127](https://www.github.com/googleapis/python-talent/issues/1127)) ([#109](https://www.github.com/googleapis/python-talent/issues/109)) ([fe89307](https://www.github.com/googleapis/python-talent/commit/fe89307a7288e02aaeadb4d582a4b0bd7aa1d221)), closes [#1126](https://www.github.com/googleapis/python-talent/issues/1126)
+
## [2.1.0](https://www.github.com/googleapis/python-talent/compare/v2.0.0...v2.1.0) (2021-02-11)
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index 12046067..124cba6b 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -68,10 +68,12 @@ Using ``nox``
We use `nox `__ to instrument our tests.
- To test your changes, run unit tests with ``nox``::
+ $ nox -s unit
+
+- To run a single unit test::
+
+ $ nox -s unit-3.9 -- -k
- $ nox -s unit-2.7
- $ nox -s unit-3.7
- $ ...
.. note::
@@ -93,8 +95,12 @@ On Debian/Ubuntu::
************
Coding Style
************
+- We use the automatic code formatter ``black``. You can run it using
+ the nox session ``blacken``. This will eliminate many lint errors. Run via::
+
+ $ nox -s blacken
-- PEP8 compliance, with exceptions defined in the linter configuration.
+- PEP8 compliance is required, with exceptions defined in the linter configuration.
If you have ``nox`` installed, you can test that you have not introduced
any non-compliant code via::
@@ -133,34 +139,23 @@ Running System Tests
- To run system tests, you can execute::
- $ nox -s system-3.7
- $ nox -s system-2.7
+ # Run all system tests
+ $ nox -s system
+
+ # Run a single system test
+ $ nox -s system-3.8 -- -k
+
.. note::
- System tests are only configured to run under Python 2.7 and
- Python 3.7. For expediency, we do not run them in older versions
- of Python 3.
+ System tests are only configured to run under Python 3.8.
+ For expediency, we do not run them in older versions of Python 3.
This alone will not run the tests. You'll need to change some local
auth settings and change some configuration in your project to
run all the tests.
-- System tests will be run against an actual project and
- so you'll need to provide some environment variables to facilitate
- authentication to your project:
-
- - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file;
- Such a file can be downloaded directly from the developer's console by clicking
- "Generate new JSON key". See private key
- `docs `__
- for more details.
-
-- Once you have downloaded your json keys, set the environment variable
- ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file::
-
- $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json"
-
+- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__.
*************
Test Coverage
@@ -218,8 +213,8 @@ Supported versions can be found in our ``noxfile.py`` `config`_.
.. _config: https://github.com/googleapis/python-talent/blob/master/noxfile.py
-We also explicitly decided to support Python 3 beginning with version
-3.6. Reasons for this include:
+We also explicitly decided to support Python 3 beginning with version 3.6.
+Reasons for this include:
- Encouraging use of newest versions of Python 3
- Taking the lead of `prominent`_ open-source `projects`_
diff --git a/LICENSE b/LICENSE
index a8ee855d..d6456956 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,7 @@
- Apache License
+
+ Apache License
Version 2.0, January 2004
- https://www.apache.org/licenses/
+ http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
@@ -192,7 +193,7 @@
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
+ 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,
diff --git a/MANIFEST.in b/MANIFEST.in
index e9e29d12..e783f4c6 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -16,10 +16,10 @@
# Generated by synthtool. DO NOT EDIT!
include README.rst LICENSE
-recursive-include google *.json *.proto
+recursive-include google *.json *.proto py.typed
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
+prune scripts/readme-gen
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 00000000..8b58ae9c
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,7 @@
+# Security Policy
+
+To report a security issue, please use [g.co/vulnz](https://g.co/vulnz).
+
+The Google Security Team will respond within 5 working days of your report on g.co/vulnz.
+
+We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue.
diff --git a/UPGRADING.md b/UPGRADING.md
index 9a5a84b4..60dcddc5 100644
--- a/UPGRADING.md
+++ b/UPGRADING.md
@@ -13,9 +13,9 @@ The 1.0.0 release requires Python 3.6+.
> **WARNING**: Breaking change
Methods expect request objects. We provide a script that will convert most common use cases.
-* Install the library
+* Install the library with `libcst.`
```py
-python3 -m pip install google-cloud-talent
+python3 -m pip install google-cloud-talent[libcst]
```
* The scripts `fixup_talent_v4beta1_keywords.py` shipped with the library. It expects
@@ -155,4 +155,4 @@ request = talent_v4.SearchJobsRequest(
)
for response_item in client.search_jobs(request=request).matching_jobs:
# ...
-```
\ No newline at end of file
+```
diff --git a/docs/_static/custom.css b/docs/_static/custom.css
index 0abaf229..b0a29546 100644
--- a/docs/_static/custom.css
+++ b/docs/_static/custom.css
@@ -1,4 +1,20 @@
div#python2-eol {
border-color: red;
border-width: medium;
-}
\ No newline at end of file
+}
+
+/* Ensure minimum width for 'Parameters' / 'Returns' column */
+dl.field-list > dt {
+ min-width: 100px
+}
+
+/* Insert space between methods for readability */
+dl.method {
+ padding-top: 10px;
+ padding-bottom: 10px
+}
+
+/* Insert empty space between classes */
+dl.class {
+ padding-bottom: 50px
+}
diff --git a/docs/conf.py b/docs/conf.py
index 6f1a41b2..1b57beeb 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,4 +1,17 @@
# -*- coding: utf-8 -*-
+# Copyright 2021 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
#
# google-cloud-talent documentation build configuration file
#
@@ -67,9 +80,9 @@
master_doc = "index"
# General information about the project.
-project = u"google-cloud-talent"
-copyright = u"2019, Google"
-author = u"Google APIs"
+project = "google-cloud-talent"
+copyright = "2019, Google"
+author = "Google APIs"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -268,7 +281,7 @@
(
master_doc,
"google-cloud-talent.tex",
- u"google-cloud-talent Documentation",
+ "google-cloud-talent Documentation",
author,
"manual",
)
@@ -303,7 +316,7 @@
(
master_doc,
"google-cloud-talent",
- u"google-cloud-talent Documentation",
+ "google-cloud-talent Documentation",
[author],
1,
)
@@ -322,7 +335,7 @@
(
master_doc,
"google-cloud-talent",
- u"google-cloud-talent Documentation",
+ "google-cloud-talent Documentation",
author,
"google-cloud-talent",
"google-cloud-talent Library",
@@ -350,6 +363,7 @@
"google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,),
"grpc": ("https://grpc.github.io/grpc/python/", None),
"proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None),
+ "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None),
}
diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst
index 1cb29d4c..536d17b2 100644
--- a/docs/multiprocessing.rst
+++ b/docs/multiprocessing.rst
@@ -1,7 +1,7 @@
.. note::
- Because this client uses :mod:`grpcio` library, it is safe to
+ Because this client uses :mod:`grpc` library, it is safe to
share instances across threads. In multiprocessing scenarios, the best
practice is to create client instances *after* the invocation of
- :func:`os.fork` by :class:`multiprocessing.Pool` or
+ :func:`os.fork` by :class:`multiprocessing.pool.Pool` or
:class:`multiprocessing.Process`.
diff --git a/docs/talent_v4/company_service.rst b/docs/talent_v4/company_service.rst
new file mode 100644
index 00000000..7d9acfc3
--- /dev/null
+++ b/docs/talent_v4/company_service.rst
@@ -0,0 +1,10 @@
+CompanyService
+--------------------------------
+
+.. automodule:: google.cloud.talent_v4.services.company_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4.services.company_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4/completion.rst b/docs/talent_v4/completion.rst
new file mode 100644
index 00000000..3044c5a8
--- /dev/null
+++ b/docs/talent_v4/completion.rst
@@ -0,0 +1,6 @@
+Completion
+----------------------------
+
+.. automodule:: google.cloud.talent_v4.services.completion
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4/event_service.rst b/docs/talent_v4/event_service.rst
new file mode 100644
index 00000000..1c90bae1
--- /dev/null
+++ b/docs/talent_v4/event_service.rst
@@ -0,0 +1,6 @@
+EventService
+------------------------------
+
+.. automodule:: google.cloud.talent_v4.services.event_service
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4/job_service.rst b/docs/talent_v4/job_service.rst
new file mode 100644
index 00000000..d8824847
--- /dev/null
+++ b/docs/talent_v4/job_service.rst
@@ -0,0 +1,10 @@
+JobService
+----------------------------
+
+.. automodule:: google.cloud.talent_v4.services.job_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4.services.job_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4/services.rst b/docs/talent_v4/services.rst
index 5efed8a2..b2eb192c 100644
--- a/docs/talent_v4/services.rst
+++ b/docs/talent_v4/services.rst
@@ -1,18 +1,10 @@
Services for Google Cloud Talent v4 API
=======================================
+.. toctree::
+ :maxdepth: 2
-.. automodule:: google.cloud.talent_v4.services.company_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4.services.completion
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4.services.event_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4.services.job_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4.services.tenant_service
- :members:
- :inherited-members:
+ company_service
+ completion
+ event_service
+ job_service
+ tenant_service
diff --git a/docs/talent_v4/tenant_service.rst b/docs/talent_v4/tenant_service.rst
new file mode 100644
index 00000000..26f09b23
--- /dev/null
+++ b/docs/talent_v4/tenant_service.rst
@@ -0,0 +1,10 @@
+TenantService
+-------------------------------
+
+.. automodule:: google.cloud.talent_v4.services.tenant_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4.services.tenant_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4/types.rst b/docs/talent_v4/types.rst
index 559524b9..9c08edc9 100644
--- a/docs/talent_v4/types.rst
+++ b/docs/talent_v4/types.rst
@@ -3,4 +3,5 @@ Types for Google Cloud Talent v4 API
.. automodule:: google.cloud.talent_v4.types
:members:
+ :undoc-members:
:show-inheritance:
diff --git a/docs/talent_v4beta1/application_service.rst b/docs/talent_v4beta1/application_service.rst
new file mode 100644
index 00000000..58e0529b
--- /dev/null
+++ b/docs/talent_v4beta1/application_service.rst
@@ -0,0 +1,10 @@
+ApplicationService
+------------------------------------
+
+.. automodule:: google.cloud.talent_v4beta1.services.application_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4beta1.services.application_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4beta1/company_service.rst b/docs/talent_v4beta1/company_service.rst
new file mode 100644
index 00000000..b77843f6
--- /dev/null
+++ b/docs/talent_v4beta1/company_service.rst
@@ -0,0 +1,10 @@
+CompanyService
+--------------------------------
+
+.. automodule:: google.cloud.talent_v4beta1.services.company_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4beta1.services.company_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4beta1/completion.rst b/docs/talent_v4beta1/completion.rst
new file mode 100644
index 00000000..764a23f3
--- /dev/null
+++ b/docs/talent_v4beta1/completion.rst
@@ -0,0 +1,6 @@
+Completion
+----------------------------
+
+.. automodule:: google.cloud.talent_v4beta1.services.completion
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4beta1/event_service.rst b/docs/talent_v4beta1/event_service.rst
new file mode 100644
index 00000000..8e489d4c
--- /dev/null
+++ b/docs/talent_v4beta1/event_service.rst
@@ -0,0 +1,6 @@
+EventService
+------------------------------
+
+.. automodule:: google.cloud.talent_v4beta1.services.event_service
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4beta1/job_service.rst b/docs/talent_v4beta1/job_service.rst
new file mode 100644
index 00000000..605042c2
--- /dev/null
+++ b/docs/talent_v4beta1/job_service.rst
@@ -0,0 +1,10 @@
+JobService
+----------------------------
+
+.. automodule:: google.cloud.talent_v4beta1.services.job_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4beta1.services.job_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4beta1/profile_service.rst b/docs/talent_v4beta1/profile_service.rst
new file mode 100644
index 00000000..cf00d2d8
--- /dev/null
+++ b/docs/talent_v4beta1/profile_service.rst
@@ -0,0 +1,10 @@
+ProfileService
+--------------------------------
+
+.. automodule:: google.cloud.talent_v4beta1.services.profile_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4beta1.services.profile_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4beta1/services.rst b/docs/talent_v4beta1/services.rst
index babbaa4e..019f928f 100644
--- a/docs/talent_v4beta1/services.rst
+++ b/docs/talent_v4beta1/services.rst
@@ -1,24 +1,12 @@
Services for Google Cloud Talent v4beta1 API
============================================
+.. toctree::
+ :maxdepth: 2
-.. automodule:: google.cloud.talent_v4beta1.services.application_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4beta1.services.company_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4beta1.services.completion
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4beta1.services.event_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4beta1.services.job_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4beta1.services.profile_service
- :members:
- :inherited-members:
-.. automodule:: google.cloud.talent_v4beta1.services.tenant_service
- :members:
- :inherited-members:
+ application_service
+ company_service
+ completion
+ event_service
+ job_service
+ profile_service
+ tenant_service
diff --git a/docs/talent_v4beta1/tenant_service.rst b/docs/talent_v4beta1/tenant_service.rst
new file mode 100644
index 00000000..cc5630b3
--- /dev/null
+++ b/docs/talent_v4beta1/tenant_service.rst
@@ -0,0 +1,10 @@
+TenantService
+-------------------------------
+
+.. automodule:: google.cloud.talent_v4beta1.services.tenant_service
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.talent_v4beta1.services.tenant_service.pagers
+ :members:
+ :inherited-members:
diff --git a/docs/talent_v4beta1/types.rst b/docs/talent_v4beta1/types.rst
index 170f4b18..e6abbcac 100644
--- a/docs/talent_v4beta1/types.rst
+++ b/docs/talent_v4beta1/types.rst
@@ -3,4 +3,5 @@ Types for Google Cloud Talent v4beta1 API
.. automodule:: google.cloud.talent_v4beta1.types
:members:
+ :undoc-members:
:show-inheritance:
diff --git a/google/cloud/talent/__init__.py b/google/cloud/talent/__init__.py
index 13571c97..cabb8fb8 100644
--- a/google/cloud/talent/__init__.py
+++ b/google/cloud/talent/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,44 +14,45 @@
# limitations under the License.
#
+from google.cloud.talent_v4.services.company_service.client import CompanyServiceClient
from google.cloud.talent_v4.services.company_service.async_client import (
CompanyServiceAsyncClient,
)
-from google.cloud.talent_v4.services.company_service.client import CompanyServiceClient
+from google.cloud.talent_v4.services.completion.client import CompletionClient
from google.cloud.talent_v4.services.completion.async_client import (
CompletionAsyncClient,
)
-from google.cloud.talent_v4.services.completion.client import CompletionClient
+from google.cloud.talent_v4.services.event_service.client import EventServiceClient
from google.cloud.talent_v4.services.event_service.async_client import (
EventServiceAsyncClient,
)
-from google.cloud.talent_v4.services.event_service.client import EventServiceClient
+from google.cloud.talent_v4.services.job_service.client import JobServiceClient
from google.cloud.talent_v4.services.job_service.async_client import (
JobServiceAsyncClient,
)
-from google.cloud.talent_v4.services.job_service.client import JobServiceClient
+from google.cloud.talent_v4.services.tenant_service.client import TenantServiceClient
from google.cloud.talent_v4.services.tenant_service.async_client import (
TenantServiceAsyncClient,
)
-from google.cloud.talent_v4.services.tenant_service.client import TenantServiceClient
+
from google.cloud.talent_v4.types.common import BatchOperationMetadata
-from google.cloud.talent_v4.types.common import CommuteMethod
-from google.cloud.talent_v4.types.common import CompanySize
from google.cloud.talent_v4.types.common import CompensationInfo
from google.cloud.talent_v4.types.common import CustomAttribute
-from google.cloud.talent_v4.types.common import DegreeType
from google.cloud.talent_v4.types.common import DeviceInfo
+from google.cloud.talent_v4.types.common import Location
+from google.cloud.talent_v4.types.common import RequestMetadata
+from google.cloud.talent_v4.types.common import ResponseMetadata
+from google.cloud.talent_v4.types.common import SpellingCorrection
+from google.cloud.talent_v4.types.common import TimestampRange
+from google.cloud.talent_v4.types.common import CommuteMethod
+from google.cloud.talent_v4.types.common import CompanySize
+from google.cloud.talent_v4.types.common import DegreeType
from google.cloud.talent_v4.types.common import EmploymentType
from google.cloud.talent_v4.types.common import HtmlSanitization
from google.cloud.talent_v4.types.common import JobBenefit
from google.cloud.talent_v4.types.common import JobCategory
from google.cloud.talent_v4.types.common import JobLevel
-from google.cloud.talent_v4.types.common import Location
from google.cloud.talent_v4.types.common import PostingRegion
-from google.cloud.talent_v4.types.common import RequestMetadata
-from google.cloud.talent_v4.types.common import ResponseMetadata
-from google.cloud.talent_v4.types.common import SpellingCorrection
-from google.cloud.talent_v4.types.common import TimestampRange
from google.cloud.talent_v4.types.common import Visibility
from google.cloud.talent_v4.types.company import Company
from google.cloud.talent_v4.types.company_service import CreateCompanyRequest
@@ -83,12 +83,12 @@
from google.cloud.talent_v4.types.job_service import DeleteJobRequest
from google.cloud.talent_v4.types.job_service import GetJobRequest
from google.cloud.talent_v4.types.job_service import JobResult
-from google.cloud.talent_v4.types.job_service import JobView
from google.cloud.talent_v4.types.job_service import ListJobsRequest
from google.cloud.talent_v4.types.job_service import ListJobsResponse
from google.cloud.talent_v4.types.job_service import SearchJobsRequest
from google.cloud.talent_v4.types.job_service import SearchJobsResponse
from google.cloud.talent_v4.types.job_service import UpdateJobRequest
+from google.cloud.talent_v4.types.job_service import JobView
from google.cloud.talent_v4.types.tenant import Tenant
from google.cloud.talent_v4.types.tenant_service import CreateTenantRequest
from google.cloud.talent_v4.types.tenant_service import DeleteTenantRequest
@@ -98,75 +98,75 @@
from google.cloud.talent_v4.types.tenant_service import UpdateTenantRequest
__all__ = (
- "BatchCreateJobsRequest",
- "BatchCreateJobsResponse",
- "BatchDeleteJobsRequest",
- "BatchDeleteJobsResponse",
- "BatchOperationMetadata",
- "BatchUpdateJobsRequest",
- "BatchUpdateJobsResponse",
- "ClientEvent",
- "CommuteFilter",
- "CommuteMethod",
- "Company",
- "CompanyServiceAsyncClient",
"CompanyServiceClient",
- "CompanySize",
- "CompensationFilter",
- "CompensationInfo",
- "CompleteQueryRequest",
- "CompleteQueryResponse",
- "CompletionAsyncClient",
+ "CompanyServiceAsyncClient",
"CompletionClient",
- "CreateClientEventRequest",
- "CreateCompanyRequest",
- "CreateJobRequest",
- "CreateTenantRequest",
+ "CompletionAsyncClient",
+ "EventServiceClient",
+ "EventServiceAsyncClient",
+ "JobServiceClient",
+ "JobServiceAsyncClient",
+ "TenantServiceClient",
+ "TenantServiceAsyncClient",
+ "BatchOperationMetadata",
+ "CompensationInfo",
"CustomAttribute",
- "DegreeType",
- "DeleteCompanyRequest",
- "DeleteJobRequest",
- "DeleteTenantRequest",
"DeviceInfo",
+ "Location",
+ "RequestMetadata",
+ "ResponseMetadata",
+ "SpellingCorrection",
+ "TimestampRange",
+ "CommuteMethod",
+ "CompanySize",
+ "DegreeType",
"EmploymentType",
- "EventServiceAsyncClient",
- "EventServiceClient",
- "GetCompanyRequest",
- "GetJobRequest",
- "GetTenantRequest",
- "HistogramQuery",
- "HistogramQueryResult",
"HtmlSanitization",
- "Job",
"JobBenefit",
"JobCategory",
- "JobEvent",
"JobLevel",
- "JobQuery",
- "JobResult",
- "JobServiceAsyncClient",
- "JobServiceClient",
- "JobView",
+ "PostingRegion",
+ "Visibility",
+ "Company",
+ "CreateCompanyRequest",
+ "DeleteCompanyRequest",
+ "GetCompanyRequest",
"ListCompaniesRequest",
"ListCompaniesResponse",
+ "UpdateCompanyRequest",
+ "CompleteQueryRequest",
+ "CompleteQueryResponse",
+ "ClientEvent",
+ "JobEvent",
+ "CreateClientEventRequest",
+ "CommuteFilter",
+ "CompensationFilter",
+ "JobQuery",
+ "LocationFilter",
+ "HistogramQuery",
+ "HistogramQueryResult",
+ "Job",
+ "BatchCreateJobsRequest",
+ "BatchCreateJobsResponse",
+ "BatchDeleteJobsRequest",
+ "BatchDeleteJobsResponse",
+ "BatchUpdateJobsRequest",
+ "BatchUpdateJobsResponse",
+ "CreateJobRequest",
+ "DeleteJobRequest",
+ "GetJobRequest",
+ "JobResult",
"ListJobsRequest",
"ListJobsResponse",
- "ListTenantsRequest",
- "ListTenantsResponse",
- "Location",
- "LocationFilter",
- "PostingRegion",
- "RequestMetadata",
- "ResponseMetadata",
"SearchJobsRequest",
"SearchJobsResponse",
- "SpellingCorrection",
- "Tenant",
- "TenantServiceAsyncClient",
- "TenantServiceClient",
- "TimestampRange",
- "UpdateCompanyRequest",
"UpdateJobRequest",
+ "JobView",
+ "Tenant",
+ "CreateTenantRequest",
+ "DeleteTenantRequest",
+ "GetTenantRequest",
+ "ListTenantsRequest",
+ "ListTenantsResponse",
"UpdateTenantRequest",
- "Visibility",
)
diff --git a/google/cloud/talent_v4/__init__.py b/google/cloud/talent_v4/__init__.py
index 5d959d15..cf1762b6 100644
--- a/google/cloud/talent_v4/__init__.py
+++ b/google/cloud/talent_v4/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,28 +15,34 @@
#
from .services.company_service import CompanyServiceClient
+from .services.company_service import CompanyServiceAsyncClient
from .services.completion import CompletionClient
+from .services.completion import CompletionAsyncClient
from .services.event_service import EventServiceClient
+from .services.event_service import EventServiceAsyncClient
from .services.job_service import JobServiceClient
+from .services.job_service import JobServiceAsyncClient
from .services.tenant_service import TenantServiceClient
+from .services.tenant_service import TenantServiceAsyncClient
+
from .types.common import BatchOperationMetadata
-from .types.common import CommuteMethod
-from .types.common import CompanySize
from .types.common import CompensationInfo
from .types.common import CustomAttribute
-from .types.common import DegreeType
from .types.common import DeviceInfo
+from .types.common import Location
+from .types.common import RequestMetadata
+from .types.common import ResponseMetadata
+from .types.common import SpellingCorrection
+from .types.common import TimestampRange
+from .types.common import CommuteMethod
+from .types.common import CompanySize
+from .types.common import DegreeType
from .types.common import EmploymentType
from .types.common import HtmlSanitization
from .types.common import JobBenefit
from .types.common import JobCategory
from .types.common import JobLevel
-from .types.common import Location
from .types.common import PostingRegion
-from .types.common import RequestMetadata
-from .types.common import ResponseMetadata
-from .types.common import SpellingCorrection
-from .types.common import TimestampRange
from .types.common import Visibility
from .types.company import Company
from .types.company_service import CreateCompanyRequest
@@ -68,12 +73,12 @@
from .types.job_service import DeleteJobRequest
from .types.job_service import GetJobRequest
from .types.job_service import JobResult
-from .types.job_service import JobView
from .types.job_service import ListJobsRequest
from .types.job_service import ListJobsResponse
from .types.job_service import SearchJobsRequest
from .types.job_service import SearchJobsResponse
from .types.job_service import UpdateJobRequest
+from .types.job_service import JobView
from .types.tenant import Tenant
from .types.tenant_service import CreateTenantRequest
from .types.tenant_service import DeleteTenantRequest
@@ -82,8 +87,12 @@
from .types.tenant_service import ListTenantsResponse
from .types.tenant_service import UpdateTenantRequest
-
__all__ = (
+ "CompanyServiceAsyncClient",
+ "CompletionAsyncClient",
+ "EventServiceAsyncClient",
+ "JobServiceAsyncClient",
+ "TenantServiceAsyncClient",
"BatchCreateJobsRequest",
"BatchCreateJobsResponse",
"BatchDeleteJobsRequest",
@@ -101,6 +110,7 @@
"CompensationInfo",
"CompleteQueryRequest",
"CompleteQueryResponse",
+ "CompletionClient",
"CreateClientEventRequest",
"CreateCompanyRequest",
"CreateJobRequest",
@@ -149,5 +159,4 @@
"UpdateJobRequest",
"UpdateTenantRequest",
"Visibility",
- "CompletionClient",
)
diff --git a/google/cloud/talent_v4/gapic_metadata.json b/google/cloud/talent_v4/gapic_metadata.json
new file mode 100644
index 00000000..3396f471
--- /dev/null
+++ b/google/cloud/talent_v4/gapic_metadata.json
@@ -0,0 +1,299 @@
+ {
+ "comment": "This file maps proto services/RPCs to the corresponding library clients/methods",
+ "language": "python",
+ "libraryPackage": "google.cloud.talent_v4",
+ "protoPackage": "google.cloud.talent.v4",
+ "schema": "1.0",
+ "services": {
+ "CompanyService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "CompanyServiceClient",
+ "rpcs": {
+ "CreateCompany": {
+ "methods": [
+ "create_company"
+ ]
+ },
+ "DeleteCompany": {
+ "methods": [
+ "delete_company"
+ ]
+ },
+ "GetCompany": {
+ "methods": [
+ "get_company"
+ ]
+ },
+ "ListCompanies": {
+ "methods": [
+ "list_companies"
+ ]
+ },
+ "UpdateCompany": {
+ "methods": [
+ "update_company"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "CompanyServiceAsyncClient",
+ "rpcs": {
+ "CreateCompany": {
+ "methods": [
+ "create_company"
+ ]
+ },
+ "DeleteCompany": {
+ "methods": [
+ "delete_company"
+ ]
+ },
+ "GetCompany": {
+ "methods": [
+ "get_company"
+ ]
+ },
+ "ListCompanies": {
+ "methods": [
+ "list_companies"
+ ]
+ },
+ "UpdateCompany": {
+ "methods": [
+ "update_company"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "Completion": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "CompletionClient",
+ "rpcs": {
+ "CompleteQuery": {
+ "methods": [
+ "complete_query"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "CompletionAsyncClient",
+ "rpcs": {
+ "CompleteQuery": {
+ "methods": [
+ "complete_query"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "EventService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "EventServiceClient",
+ "rpcs": {
+ "CreateClientEvent": {
+ "methods": [
+ "create_client_event"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "EventServiceAsyncClient",
+ "rpcs": {
+ "CreateClientEvent": {
+ "methods": [
+ "create_client_event"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "JobService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "JobServiceClient",
+ "rpcs": {
+ "BatchCreateJobs": {
+ "methods": [
+ "batch_create_jobs"
+ ]
+ },
+ "BatchDeleteJobs": {
+ "methods": [
+ "batch_delete_jobs"
+ ]
+ },
+ "BatchUpdateJobs": {
+ "methods": [
+ "batch_update_jobs"
+ ]
+ },
+ "CreateJob": {
+ "methods": [
+ "create_job"
+ ]
+ },
+ "DeleteJob": {
+ "methods": [
+ "delete_job"
+ ]
+ },
+ "GetJob": {
+ "methods": [
+ "get_job"
+ ]
+ },
+ "ListJobs": {
+ "methods": [
+ "list_jobs"
+ ]
+ },
+ "SearchJobs": {
+ "methods": [
+ "search_jobs"
+ ]
+ },
+ "SearchJobsForAlert": {
+ "methods": [
+ "search_jobs_for_alert"
+ ]
+ },
+ "UpdateJob": {
+ "methods": [
+ "update_job"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "JobServiceAsyncClient",
+ "rpcs": {
+ "BatchCreateJobs": {
+ "methods": [
+ "batch_create_jobs"
+ ]
+ },
+ "BatchDeleteJobs": {
+ "methods": [
+ "batch_delete_jobs"
+ ]
+ },
+ "BatchUpdateJobs": {
+ "methods": [
+ "batch_update_jobs"
+ ]
+ },
+ "CreateJob": {
+ "methods": [
+ "create_job"
+ ]
+ },
+ "DeleteJob": {
+ "methods": [
+ "delete_job"
+ ]
+ },
+ "GetJob": {
+ "methods": [
+ "get_job"
+ ]
+ },
+ "ListJobs": {
+ "methods": [
+ "list_jobs"
+ ]
+ },
+ "SearchJobs": {
+ "methods": [
+ "search_jobs"
+ ]
+ },
+ "SearchJobsForAlert": {
+ "methods": [
+ "search_jobs_for_alert"
+ ]
+ },
+ "UpdateJob": {
+ "methods": [
+ "update_job"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "TenantService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "TenantServiceClient",
+ "rpcs": {
+ "CreateTenant": {
+ "methods": [
+ "create_tenant"
+ ]
+ },
+ "DeleteTenant": {
+ "methods": [
+ "delete_tenant"
+ ]
+ },
+ "GetTenant": {
+ "methods": [
+ "get_tenant"
+ ]
+ },
+ "ListTenants": {
+ "methods": [
+ "list_tenants"
+ ]
+ },
+ "UpdateTenant": {
+ "methods": [
+ "update_tenant"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "TenantServiceAsyncClient",
+ "rpcs": {
+ "CreateTenant": {
+ "methods": [
+ "create_tenant"
+ ]
+ },
+ "DeleteTenant": {
+ "methods": [
+ "delete_tenant"
+ ]
+ },
+ "GetTenant": {
+ "methods": [
+ "get_tenant"
+ ]
+ },
+ "ListTenants": {
+ "methods": [
+ "list_tenants"
+ ]
+ },
+ "UpdateTenant": {
+ "methods": [
+ "update_tenant"
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/google/cloud/talent_v4/proto/common.proto b/google/cloud/talent_v4/proto/common.proto
deleted file mode 100644
index d187a17f..00000000
--- a/google/cloud/talent_v4/proto/common.proto
+++ /dev/null
@@ -1,860 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/field_behavior.proto";
-import "google/protobuf/timestamp.proto";
-import "google/protobuf/wrappers.proto";
-import "google/type/latlng.proto";
-import "google/type/money.proto";
-import "google/type/postal_address.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CommonProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// Message representing a period of time between two timestamps.
-message TimestampRange {
- // Begin of the period (inclusive).
- google.protobuf.Timestamp start_time = 1;
-
- // End of the period (exclusive).
- google.protobuf.Timestamp end_time = 2;
-}
-
-// An enum that represents the size of the company.
-enum CompanySize {
- // Default value if the size isn't specified.
- COMPANY_SIZE_UNSPECIFIED = 0;
-
- // The company has less than 50 employees.
- MINI = 1;
-
- // The company has between 50 and 99 employees.
- SMALL = 2;
-
- // The company has between 100 and 499 employees.
- SMEDIUM = 3;
-
- // The company has between 500 and 999 employees.
- MEDIUM = 4;
-
- // The company has between 1,000 and 4,999 employees.
- BIG = 5;
-
- // The company has between 5,000 and 9,999 employees.
- BIGGER = 6;
-
- // The company has 10,000 or more employees.
- GIANT = 7;
-}
-
-// An enum that represents employee benefits included with the job.
-enum JobBenefit {
- // Default value if the type isn't specified.
- JOB_BENEFIT_UNSPECIFIED = 0;
-
- // The job includes access to programs that support child care, such
- // as daycare.
- CHILD_CARE = 1;
-
- // The job includes dental services covered by a dental
- // insurance plan.
- DENTAL = 2;
-
- // The job offers specific benefits to domestic partners.
- DOMESTIC_PARTNER = 3;
-
- // The job allows for a flexible work schedule.
- FLEXIBLE_HOURS = 4;
-
- // The job includes health services covered by a medical insurance plan.
- MEDICAL = 5;
-
- // The job includes a life insurance plan provided by the employer or
- // available for purchase by the employee.
- LIFE_INSURANCE = 6;
-
- // The job allows for a leave of absence to a parent to care for a newborn
- // child.
- PARENTAL_LEAVE = 7;
-
- // The job includes a workplace retirement plan provided by the
- // employer or available for purchase by the employee.
- RETIREMENT_PLAN = 8;
-
- // The job allows for paid time off due to illness.
- SICK_DAYS = 9;
-
- // The job includes paid time off for vacation.
- VACATION = 10;
-
- // The job includes vision services covered by a vision
- // insurance plan.
- VISION = 11;
-}
-
-// Educational degree level defined in International Standard Classification
-// of Education (ISCED).
-enum DegreeType {
- // Default value. Represents no degree, or early childhood education.
- // Maps to ISCED code 0.
- // Ex) Kindergarten
- DEGREE_TYPE_UNSPECIFIED = 0;
-
- // Primary education which is typically the first stage of compulsory
- // education. ISCED code 1.
- // Ex) Elementary school
- PRIMARY_EDUCATION = 1;
-
- // Lower secondary education; First stage of secondary education building on
- // primary education, typically with a more subject-oriented curriculum.
- // ISCED code 2.
- // Ex) Middle school
- LOWER_SECONDARY_EDUCATION = 2;
-
- // Middle education; Second/final stage of secondary education preparing for
- // tertiary education and/or providing skills relevant to employment.
- // Usually with an increased range of subject options and streams. ISCED
- // code 3.
- // Ex) High school
- UPPER_SECONDARY_EDUCATION = 3;
-
- // Adult Remedial Education; Programmes providing learning experiences that
- // build on secondary education and prepare for labour market entry and/or
- // tertiary education. The content is broader than secondary but not as
- // complex as tertiary education. ISCED code 4.
- ADULT_REMEDIAL_EDUCATION = 4;
-
- // Associate's or equivalent; Short first tertiary programmes that are
- // typically practically-based, occupationally-specific and prepare for
- // labour market entry. These programmes may also provide a pathway to other
- // tertiary programmes. ISCED code 5.
- ASSOCIATES_OR_EQUIVALENT = 5;
-
- // Bachelor's or equivalent; Programmes designed to provide intermediate
- // academic and/or professional knowledge, skills and competencies leading
- // to a first tertiary degree or equivalent qualification. ISCED code 6.
- BACHELORS_OR_EQUIVALENT = 6;
-
- // Master's or equivalent; Programmes designed to provide advanced academic
- // and/or professional knowledge, skills and competencies leading to a
- // second tertiary degree or equivalent qualification. ISCED code 7.
- MASTERS_OR_EQUIVALENT = 7;
-
- // Doctoral or equivalent; Programmes designed primarily to lead to an
- // advanced research qualification, usually concluding with the submission
- // and defense of a substantive dissertation of publishable quality based on
- // original research. ISCED code 8.
- DOCTORAL_OR_EQUIVALENT = 8;
-}
-
-// An enum that represents the employment type of a job.
-enum EmploymentType {
- // The default value if the employment type isn't specified.
- EMPLOYMENT_TYPE_UNSPECIFIED = 0;
-
- // The job requires working a number of hours that constitute full
- // time employment, typically 40 or more hours per week.
- FULL_TIME = 1;
-
- // The job entails working fewer hours than a full time job,
- // typically less than 40 hours a week.
- PART_TIME = 2;
-
- // The job is offered as a contracted, as opposed to a salaried employee,
- // position.
- CONTRACTOR = 3;
-
- // The job is offered as a contracted position with the understanding
- // that it's converted into a full-time position at the end of the
- // contract. Jobs of this type are also returned by a search for
- // [EmploymentType.CONTRACTOR][google.cloud.talent.v4.EmploymentType.CONTRACTOR] jobs.
- CONTRACT_TO_HIRE = 4;
-
- // The job is offered as a temporary employment opportunity, usually
- // a short-term engagement.
- TEMPORARY = 5;
-
- // The job is a fixed-term opportunity for students or entry-level job
- // seekers to obtain on-the-job training, typically offered as a summer
- // position.
- INTERN = 6;
-
- // The is an opportunity for an individual to volunteer, where there's no
- // expectation of compensation for the provided services.
- VOLUNTEER = 7;
-
- // The job requires an employee to work on an as-needed basis with a
- // flexible schedule.
- PER_DIEM = 8;
-
- // The job involves employing people in remote areas and flying them
- // temporarily to the work site instead of relocating employees and their
- // families permanently.
- FLY_IN_FLY_OUT = 9;
-
- // The job does not fit any of the other listed types.
- OTHER_EMPLOYMENT_TYPE = 10;
-}
-
-// An enum that represents the required experience level required for the job.
-enum JobLevel {
- // The default value if the level isn't specified.
- JOB_LEVEL_UNSPECIFIED = 0;
-
- // Entry-level individual contributors, typically with less than 2 years of
- // experience in a similar role. Includes interns.
- ENTRY_LEVEL = 1;
-
- // Experienced individual contributors, typically with 2+ years of
- // experience in a similar role.
- EXPERIENCED = 2;
-
- // Entry- to mid-level managers responsible for managing a team of people.
- MANAGER = 3;
-
- // Senior-level managers responsible for managing teams of managers.
- DIRECTOR = 4;
-
- // Executive-level managers and above, including C-level positions.
- EXECUTIVE = 5;
-}
-
-// An enum that represents the categorization or primary focus of specific
-// role. This value is different than the "industry" associated with a role,
-// which is related to the categorization of the company listing the job.
-enum JobCategory {
- // The default value if the category isn't specified.
- JOB_CATEGORY_UNSPECIFIED = 0;
-
- // An accounting and finance job, such as an Accountant.
- ACCOUNTING_AND_FINANCE = 1;
-
- // An administrative and office job, such as an Administrative Assistant.
- ADMINISTRATIVE_AND_OFFICE = 2;
-
- // An advertising and marketing job, such as Marketing Manager.
- ADVERTISING_AND_MARKETING = 3;
-
- // An animal care job, such as Veterinarian.
- ANIMAL_CARE = 4;
-
- // An art, fashion, or design job, such as Designer.
- ART_FASHION_AND_DESIGN = 5;
-
- // A business operations job, such as Business Operations Manager.
- BUSINESS_OPERATIONS = 6;
-
- // A cleaning and facilities job, such as Custodial Staff.
- CLEANING_AND_FACILITIES = 7;
-
- // A computer and IT job, such as Systems Administrator.
- COMPUTER_AND_IT = 8;
-
- // A construction job, such as General Laborer.
- CONSTRUCTION = 9;
-
- // A customer service job, such s Cashier.
- CUSTOMER_SERVICE = 10;
-
- // An education job, such as School Teacher.
- EDUCATION = 11;
-
- // An entertainment and travel job, such as Flight Attendant.
- ENTERTAINMENT_AND_TRAVEL = 12;
-
- // A farming or outdoor job, such as Park Ranger.
- FARMING_AND_OUTDOORS = 13;
-
- // A healthcare job, such as Registered Nurse.
- HEALTHCARE = 14;
-
- // A human resources job, such as Human Resources Director.
- HUMAN_RESOURCES = 15;
-
- // An installation, maintenance, or repair job, such as Electrician.
- INSTALLATION_MAINTENANCE_AND_REPAIR = 16;
-
- // A legal job, such as Law Clerk.
- LEGAL = 17;
-
- // A management job, often used in conjunction with another category,
- // such as Store Manager.
- MANAGEMENT = 18;
-
- // A manufacturing or warehouse job, such as Assembly Technician.
- MANUFACTURING_AND_WAREHOUSE = 19;
-
- // A media, communications, or writing job, such as Media Relations.
- MEDIA_COMMUNICATIONS_AND_WRITING = 20;
-
- // An oil, gas or mining job, such as Offshore Driller.
- OIL_GAS_AND_MINING = 21;
-
- // A personal care and services job, such as Hair Stylist.
- PERSONAL_CARE_AND_SERVICES = 22;
-
- // A protective services job, such as Security Guard.
- PROTECTIVE_SERVICES = 23;
-
- // A real estate job, such as Buyer's Agent.
- REAL_ESTATE = 24;
-
- // A restaurant and hospitality job, such as Restaurant Server.
- RESTAURANT_AND_HOSPITALITY = 25;
-
- // A sales and/or retail job, such Sales Associate.
- SALES_AND_RETAIL = 26;
-
- // A science and engineering job, such as Lab Technician.
- SCIENCE_AND_ENGINEERING = 27;
-
- // A social services or non-profit job, such as Case Worker.
- SOCIAL_SERVICES_AND_NON_PROFIT = 28;
-
- // A sports, fitness, or recreation job, such as Personal Trainer.
- SPORTS_FITNESS_AND_RECREATION = 29;
-
- // A transportation or logistics job, such as Truck Driver.
- TRANSPORTATION_AND_LOGISTICS = 30;
-}
-
-// An enum that represents the job posting region. In most cases, job postings
-// don't need to specify a region. If a region is given, jobs are
-// eligible for searches in the specified region.
-enum PostingRegion {
- // If the region is unspecified, the job is only returned if it
- // matches the [LocationFilter][google.cloud.talent.v4.LocationFilter].
- POSTING_REGION_UNSPECIFIED = 0;
-
- // In addition to exact location matching, job posting is returned when the
- // [LocationFilter][google.cloud.talent.v4.LocationFilter] in the search query is in the same administrative area
- // as the returned job posting. For example, if a `ADMINISTRATIVE_AREA` job
- // is posted in "CA, USA", it's returned if [LocationFilter][google.cloud.talent.v4.LocationFilter] has
- // "Mountain View".
- //
- // Administrative area refers to top-level administrative subdivision of this
- // country. For example, US state, IT region, UK constituent nation and
- // JP prefecture.
- ADMINISTRATIVE_AREA = 1;
-
- // In addition to exact location matching, job is returned when
- // [LocationFilter][google.cloud.talent.v4.LocationFilter] in search query is in the same country as this job.
- // For example, if a `NATION_WIDE` job is posted in "USA", it's
- // returned if [LocationFilter][google.cloud.talent.v4.LocationFilter] has 'Mountain View'.
- NATION = 2;
-
- // Job allows employees to work remotely (telecommute).
- // If locations are provided with this value, the job is
- // considered as having a location, but telecommuting is allowed.
- TELECOMMUTE = 3;
-}
-
-// Deprecated. All resources are only visible to the owner.
-//
-// An enum that represents who has view access to the resource.
-enum Visibility {
- option deprecated = true;
-
- // Default value.
- VISIBILITY_UNSPECIFIED = 0;
-
- // The resource is only visible to the GCP account who owns it.
- ACCOUNT_ONLY = 1;
-
- // The resource is visible to the owner and may be visible to other
- // applications and processes at Google.
- SHARED_WITH_GOOGLE = 2;
-
- // The resource is visible to the owner and may be visible to all other API
- // clients.
- SHARED_WITH_PUBLIC = 3;
-}
-
-// Option for HTML content sanitization on user input fields, for example, job
-// description. By setting this option, user can determine whether and how
-// sanitization is performed on these fields.
-enum HtmlSanitization {
- // Default value.
- HTML_SANITIZATION_UNSPECIFIED = 0;
-
- // Disables sanitization on HTML input.
- HTML_SANITIZATION_DISABLED = 1;
-
- // Sanitizes HTML input, only accepts bold, italic, ordered list, and
- // unordered list markup tags.
- SIMPLE_FORMATTING_ONLY = 2;
-}
-
-// Method for commute.
-enum CommuteMethod {
- // Commute method isn't specified.
- COMMUTE_METHOD_UNSPECIFIED = 0;
-
- // Commute time is calculated based on driving time.
- DRIVING = 1;
-
- // Commute time is calculated based on public transit including bus, metro,
- // subway, and so on.
- TRANSIT = 2;
-}
-
-// A resource that represents a location with full geographic information.
-message Location {
- // An enum which represents the type of a location.
- enum LocationType {
- // Default value if the type isn't specified.
- LOCATION_TYPE_UNSPECIFIED = 0;
-
- // A country level location.
- COUNTRY = 1;
-
- // A state or equivalent level location.
- ADMINISTRATIVE_AREA = 2;
-
- // A county or equivalent level location.
- SUB_ADMINISTRATIVE_AREA = 3;
-
- // A city or equivalent level location.
- LOCALITY = 4;
-
- // A postal code level location.
- POSTAL_CODE = 5;
-
- // A sublocality is a subdivision of a locality, for example a city borough,
- // ward, or arrondissement. Sublocalities are usually recognized by a local
- // political authority. For example, Manhattan and Brooklyn are recognized
- // as boroughs by the City of New York, and are therefore modeled as
- // sublocalities.
- SUB_LOCALITY = 6;
-
- // A district or equivalent level location.
- SUB_LOCALITY_1 = 7;
-
- // A smaller district or equivalent level display.
- SUB_LOCALITY_2 = 8;
-
- // A neighborhood level location.
- NEIGHBORHOOD = 9;
-
- // A street address level location.
- STREET_ADDRESS = 10;
- }
-
- // The type of a location, which corresponds to the address lines field of
- // [google.type.PostalAddress][google.type.PostalAddress]. For example, "Downtown, Atlanta, GA, USA"
- // has a type of [LocationType.NEIGHBORHOOD][google.cloud.talent.v4.Location.LocationType.NEIGHBORHOOD], and "Kansas City, KS, USA"
- // has a type of [LocationType.LOCALITY][google.cloud.talent.v4.Location.LocationType.LOCALITY].
- LocationType location_type = 1;
-
- // Postal address of the location that includes human readable information,
- // such as postal delivery and payments addresses. Given a postal address,
- // a postal service can deliver items to a premises, P.O. Box, or other
- // delivery location.
- google.type.PostalAddress postal_address = 2;
-
- // An object representing a latitude/longitude pair.
- google.type.LatLng lat_lng = 3;
-
- // Radius in miles of the job location. This value is derived from the
- // location bounding box in which a circle with the specified radius
- // centered from [google.type.LatLng][google.type.LatLng] covers the area associated with the
- // job location.
- // For example, currently, "Mountain View, CA, USA" has a radius of
- // 6.17 miles.
- double radius_miles = 4;
-}
-
-// Meta information related to the job searcher or entity
-// conducting the job search. This information is used to improve the
-// performance of the service.
-message RequestMetadata {
- // Required if [allow_missing_ids][google.cloud.talent.v4.RequestMetadata.allow_missing_ids] is unset or `false`.
- //
- // The client-defined scope or source of the service call, which typically
- // is the domain on
- // which the service has been implemented and is currently being run.
- //
- // For example, if the service is being run by client Foo, Inc., on
- // job board www.foo.com and career site www.bar.com, then this field is
- // set to "foo.com" for use on the job board, and "bar.com" for use on the
- // career site.
- //
- // Note that any improvements to the model for a particular tenant site rely
- // on this field being set correctly to a unique domain.
- //
- // The maximum number of allowed characters is 255.
- string domain = 1;
-
- // Required if [allow_missing_ids][google.cloud.talent.v4.RequestMetadata.allow_missing_ids] is unset or `false`.
- //
- // A unique session identification string. A session is defined as the
- // duration of an end user's interaction with the service over a certain
- // period.
- // Obfuscate this field for privacy concerns before
- // providing it to the service.
- //
- // Note that any improvements to the model for a particular tenant site rely
- // on this field being set correctly to a unique session ID.
- //
- // The maximum number of allowed characters is 255.
- string session_id = 2;
-
- // Required if [allow_missing_ids][google.cloud.talent.v4.RequestMetadata.allow_missing_ids] is unset or `false`.
- //
- // A unique user identification string, as determined by the client.
- // To have the strongest positive impact on search quality
- // make sure the client-level is unique.
- // Obfuscate this field for privacy concerns before
- // providing it to the service.
- //
- // Note that any improvements to the model for a particular tenant site rely
- // on this field being set correctly to a unique user ID.
- //
- // The maximum number of allowed characters is 255.
- string user_id = 3;
-
- // Only set when any of [domain][google.cloud.talent.v4.RequestMetadata.domain], [session_id][google.cloud.talent.v4.RequestMetadata.session_id] and [user_id][google.cloud.talent.v4.RequestMetadata.user_id] isn't
- // available for some reason. It is highly recommended not to set this field
- // and provide accurate [domain][google.cloud.talent.v4.RequestMetadata.domain], [session_id][google.cloud.talent.v4.RequestMetadata.session_id] and [user_id][google.cloud.talent.v4.RequestMetadata.user_id] for the
- // best service experience.
- bool allow_missing_ids = 4;
-
- // The type of device used by the job seeker at the time of the call to the
- // service.
- DeviceInfo device_info = 5;
-}
-
-// Additional information returned to client, such as debugging information.
-message ResponseMetadata {
- // A unique id associated with this call.
- // This id is logged for tracking purposes.
- string request_id = 1;
-}
-
-// Device information collected from the job seeker, candidate, or
-// other entity conducting the job search. Providing this information improves
-// the quality of the search results across devices.
-message DeviceInfo {
- // An enumeration describing an API access portal and exposure mechanism.
- enum DeviceType {
- // The device type isn't specified.
- DEVICE_TYPE_UNSPECIFIED = 0;
-
- // A desktop web browser, such as, Chrome, Firefox, Safari, or Internet
- // Explorer)
- WEB = 1;
-
- // A mobile device web browser, such as a phone or tablet with a Chrome
- // browser.
- MOBILE_WEB = 2;
-
- // An Android device native application.
- ANDROID = 3;
-
- // An iOS device native application.
- IOS = 4;
-
- // A bot, as opposed to a device operated by human beings, such as a web
- // crawler.
- BOT = 5;
-
- // Other devices types.
- OTHER = 6;
- }
-
- // Type of the device.
- DeviceType device_type = 1;
-
- // A device-specific ID. The ID must be a unique identifier that
- // distinguishes the device from other devices.
- string id = 2;
-}
-
-// Custom attribute values that are either filterable or non-filterable.
-message CustomAttribute {
- // Exactly one of [string_values][google.cloud.talent.v4.CustomAttribute.string_values] or [long_values][google.cloud.talent.v4.CustomAttribute.long_values] must be specified.
- //
- // This field is used to perform a string match (`CASE_SENSITIVE_MATCH` or
- // `CASE_INSENSITIVE_MATCH`) search.
- // For filterable `string_value`s, a maximum total number of 200 values
- // is allowed, with each `string_value` has a byte size of no more than
- // 500B. For unfilterable `string_values`, the maximum total byte size of
- // unfilterable `string_values` is 50KB.
- //
- // Empty string isn't allowed.
- repeated string string_values = 1;
-
- // Exactly one of [string_values][google.cloud.talent.v4.CustomAttribute.string_values] or [long_values][google.cloud.talent.v4.CustomAttribute.long_values] must be specified.
- //
- // This field is used to perform number range search.
- // (`EQ`, `GT`, `GE`, `LE`, `LT`) over filterable `long_value`.
- //
- // Currently at most 1 [long_values][google.cloud.talent.v4.CustomAttribute.long_values] is supported.
- repeated int64 long_values = 2;
-
- // If the `filterable` flag is true, the custom field values may be used for
- // custom attribute filters [JobQuery.custom_attribute_filter][google.cloud.talent.v4.JobQuery.custom_attribute_filter].
- // If false, these values may not be used for custom attribute filters.
- //
- // Default is false.
- bool filterable = 3;
-
- // If the `keyword_searchable` flag is true, the keywords in custom fields are
- // searchable by keyword match.
- // If false, the values are not searchable by keyword match.
- //
- // Default is false.
- bool keyword_searchable = 4;
-}
-
-// Spell check result.
-message SpellingCorrection {
- // Indicates if the query was corrected by the spell checker.
- bool corrected = 1;
-
- // Correction output consisting of the corrected keyword string.
- string corrected_text = 2;
-
- // Corrected output with html tags to highlight the corrected words.
- // Corrected words are called out with the "..." html tags.
- //
- // For example, the user input query is "software enginear", where the second
- // word, "enginear," is incorrect. It should be "engineer". When spelling
- // correction is enabled, this value is
- // "software engineer".
- string corrected_html = 3;
-}
-
-// Job compensation details.
-message CompensationInfo {
- // A compensation entry that represents one component of compensation, such
- // as base pay, bonus, or other compensation type.
- //
- // Annualization: One compensation entry can be annualized if
- // - it contains valid [amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount] or [range][google.cloud.talent.v4.CompensationInfo.CompensationEntry.range].
- // - and its [expected_units_per_year][google.cloud.talent.v4.CompensationInfo.CompensationEntry.expected_units_per_year] is set or can be derived.
- // Its annualized range is determined as ([amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount] or [range][google.cloud.talent.v4.CompensationInfo.CompensationEntry.range]) times
- // [expected_units_per_year][google.cloud.talent.v4.CompensationInfo.CompensationEntry.expected_units_per_year].
- message CompensationEntry {
- // Compensation type.
- //
- // Default is [CompensationType.COMPENSATION_TYPE_UNSPECIFIED][google.cloud.talent.v4.CompensationInfo.CompensationType.COMPENSATION_TYPE_UNSPECIFIED].
- CompensationType type = 1;
-
- // Frequency of the specified amount.
- //
- // Default is [CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED][google.cloud.talent.v4.CompensationInfo.CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED].
- CompensationUnit unit = 2;
-
- // Compensation amount. It could be a fixed amount or a floating range.
- oneof compensation_amount {
- // Compensation amount.
- google.type.Money amount = 3;
-
- // Compensation range.
- CompensationRange range = 4;
- }
-
- // Compensation description. For example, could
- // indicate equity terms or provide additional context to an estimated
- // bonus.
- string description = 5;
-
- // Expected number of units paid each year. If not specified, when
- // [Job.employment_types][google.cloud.talent.v4.Job.employment_types] is FULLTIME, a default value is inferred
- // based on [unit][google.cloud.talent.v4.CompensationInfo.CompensationEntry.unit]. Default values:
- // - HOURLY: 2080
- // - DAILY: 260
- // - WEEKLY: 52
- // - MONTHLY: 12
- // - ANNUAL: 1
- google.protobuf.DoubleValue expected_units_per_year = 6;
- }
-
- // Compensation range.
- message CompensationRange {
- // The maximum amount of compensation. If left empty, the value is set
- // to a maximal compensation value and the currency code is set to
- // match the [currency code][google.type.Money.currency_code] of
- // min_compensation.
- google.type.Money max_compensation = 2;
-
- // The minimum amount of compensation. If left empty, the value is set
- // to zero and the currency code is set to match the
- // [currency code][google.type.Money.currency_code] of max_compensation.
- google.type.Money min_compensation = 1;
- }
-
- // The type of compensation.
- //
- // For compensation amounts specified in non-monetary amounts,
- // describe the compensation scheme in the [CompensationEntry.description][google.cloud.talent.v4.CompensationInfo.CompensationEntry.description].
- //
- // For example, tipping format is described in
- // [CompensationEntry.description][google.cloud.talent.v4.CompensationInfo.CompensationEntry.description] (for example, "expect 15-20% tips based
- // on customer bill.") and an estimate of the tips provided in
- // [CompensationEntry.amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount] or [CompensationEntry.range][google.cloud.talent.v4.CompensationInfo.CompensationEntry.range] ($10 per hour).
- //
- // For example, equity is described in [CompensationEntry.description][google.cloud.talent.v4.CompensationInfo.CompensationEntry.description]
- // (for example, "1% - 2% equity vesting over 4 years, 1 year cliff") and
- // value estimated in [CompensationEntry.amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount] or
- // [CompensationEntry.range][google.cloud.talent.v4.CompensationInfo.CompensationEntry.range]. If no value estimate is possible, units are
- // [CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED][google.cloud.talent.v4.CompensationInfo.CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED] and then further
- // clarified in [CompensationEntry.description][google.cloud.talent.v4.CompensationInfo.CompensationEntry.description] field.
- enum CompensationType {
- // Default value.
- COMPENSATION_TYPE_UNSPECIFIED = 0;
-
- // Base compensation: Refers to the fixed amount of money paid to an
- // employee by an employer in return for work performed. Base compensation
- // does not include benefits, bonuses or any other potential compensation
- // from an employer.
- BASE = 1;
-
- // Bonus.
- BONUS = 2;
-
- // Signing bonus.
- SIGNING_BONUS = 3;
-
- // Equity.
- EQUITY = 4;
-
- // Profit sharing.
- PROFIT_SHARING = 5;
-
- // Commission.
- COMMISSIONS = 6;
-
- // Tips.
- TIPS = 7;
-
- // Other compensation type.
- OTHER_COMPENSATION_TYPE = 8;
- }
-
- // Pay frequency.
- enum CompensationUnit {
- // Default value.
- COMPENSATION_UNIT_UNSPECIFIED = 0;
-
- // Hourly.
- HOURLY = 1;
-
- // Daily.
- DAILY = 2;
-
- // Weekly
- WEEKLY = 3;
-
- // Monthly.
- MONTHLY = 4;
-
- // Yearly.
- YEARLY = 5;
-
- // One time.
- ONE_TIME = 6;
-
- // Other compensation units.
- OTHER_COMPENSATION_UNIT = 7;
- }
-
- // Job compensation information.
- //
- // At most one entry can be of type
- // [CompensationInfo.CompensationType.BASE][google.cloud.talent.v4.CompensationInfo.CompensationType.BASE], which is
- // referred as **base compensation entry** for the job.
- repeated CompensationEntry entries = 1;
-
- // Output only. Annualized base compensation range. Computed as base compensation entry's
- // [CompensationEntry.amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount] times
- // [CompensationEntry.expected_units_per_year][google.cloud.talent.v4.CompensationInfo.CompensationEntry.expected_units_per_year].
- //
- // See [CompensationEntry][google.cloud.talent.v4.CompensationInfo.CompensationEntry] for explanation on compensation annualization.
- CompensationRange annualized_base_compensation_range = 2 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Annualized total compensation range. Computed as all compensation entries'
- // [CompensationEntry.amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount] times
- // [CompensationEntry.expected_units_per_year][google.cloud.talent.v4.CompensationInfo.CompensationEntry.expected_units_per_year].
- //
- // See [CompensationEntry][google.cloud.talent.v4.CompensationInfo.CompensationEntry] for explanation on compensation annualization.
- CompensationRange annualized_total_compensation_range = 3 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
-
-// Metadata used for long running operations returned by CTS batch APIs.
-// It's used to replace [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata].
-message BatchOperationMetadata {
- enum State {
- // Default value.
- STATE_UNSPECIFIED = 0;
-
- // The batch operation is being prepared for processing.
- INITIALIZING = 1;
-
- // The batch operation is actively being processed.
- PROCESSING = 2;
-
- // The batch operation is processed, and at least one item has been
- // successfully processed.
- SUCCEEDED = 3;
-
- // The batch operation is done and no item has been successfully processed.
- FAILED = 4;
-
- // The batch operation is in the process of cancelling after
- // [google.longrunning.Operations.CancelOperation][google.longrunning.Operations.CancelOperation] is called.
- CANCELLING = 5;
-
- // The batch operation is done after
- // [google.longrunning.Operations.CancelOperation][google.longrunning.Operations.CancelOperation] is called. Any items
- // processed before cancelling are returned in the response.
- CANCELLED = 6;
- }
-
- // The state of a long running operation.
- State state = 1;
-
- // More detailed information about operation state.
- string state_description = 2;
-
- // Count of successful item(s) inside an operation.
- int32 success_count = 3;
-
- // Count of failed item(s) inside an operation.
- int32 failure_count = 4;
-
- // Count of total item(s) inside an operation.
- int32 total_count = 5;
-
- // The time when the batch operation is created.
- google.protobuf.Timestamp create_time = 6;
-
- // The time when the batch operation status is updated. The metadata and the
- // [update_time][google.cloud.talent.v4.BatchOperationMetadata.update_time] is refreshed every minute otherwise cached data is
- // returned.
- google.protobuf.Timestamp update_time = 7;
-
- // The time when the batch operation is finished and
- // [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to `true`.
- google.protobuf.Timestamp end_time = 8;
-}
diff --git a/google/cloud/talent_v4/proto/company.proto b/google/cloud/talent_v4/proto/company.proto
deleted file mode 100644
index c6b61a2c..00000000
--- a/google/cloud/talent_v4/proto/company.proto
+++ /dev/null
@@ -1,115 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4/common.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CompanyProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A Company resource represents a company in the service. A company is the
-// entity that owns job postings, that is, the hiring entity responsible for
-// employing applicants for the job position.
-message Company {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Company"
- pattern: "projects/{project}/tenants/{tenant}/companies/{company}"
- };
-
- // Derived details about the company.
- message DerivedInfo {
- // A structured headquarters location of the company, resolved from
- // [Company.headquarters_address][google.cloud.talent.v4.Company.headquarters_address] if provided.
- Location headquarters_location = 1;
- }
-
- // Required during company update.
- //
- // The resource name for a company. This is generated by the service when a
- // company is created.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/foo/tenants/bar/companies/baz".
- string name = 1;
-
- // Required. The display name of the company, for example, "Google LLC".
- string display_name = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Required. Client side company identifier, used to uniquely identify the
- // company.
- //
- // The maximum number of allowed characters is 255.
- string external_id = 3 [(google.api.field_behavior) = REQUIRED];
-
- // The employer's company size.
- CompanySize size = 4;
-
- // The street address of the company's main headquarters, which may be
- // different from the job location. The service attempts
- // to geolocate the provided address, and populates a more specific
- // location wherever possible in [DerivedInfo.headquarters_location][google.cloud.talent.v4.Company.DerivedInfo.headquarters_location].
- string headquarters_address = 5;
-
- // Set to true if it is the hiring agency that post jobs for other
- // employers.
- //
- // Defaults to false if not provided.
- bool hiring_agency = 6;
-
- // Equal Employment Opportunity legal disclaimer text to be
- // associated with all jobs, and typically to be displayed in all
- // roles.
- //
- // The maximum number of allowed characters is 500.
- string eeo_text = 7;
-
- // The URI representing the company's primary web site or home page,
- // for example, "https://www.google.com".
- //
- // The maximum number of allowed characters is 255.
- string website_uri = 8;
-
- // The URI to employer's career site or careers page on the employer's web
- // site, for example, "https://careers.google.com".
- string career_site_uri = 9;
-
- // A URI that hosts the employer's company logo.
- string image_uri = 10;
-
- // A list of keys of filterable [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes], whose
- // corresponding `string_values` are used in keyword searches. Jobs with
- // `string_values` under these specified field keys are returned if any
- // of the values match the search keyword. Custom field values with
- // parenthesis, brackets and special symbols are not searchable as-is,
- // and those keyword queries must be surrounded by quotes.
- repeated string keyword_searchable_job_custom_attributes = 11;
-
- // Output only. Derived details about the company.
- DerivedInfo derived_info = 12 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Indicates whether a company is flagged to be suspended from
- // public availability by the service when job content appears suspicious,
- // abusive, or spammy.
- bool suspended = 13 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
diff --git a/google/cloud/talent_v4/proto/company_service.proto b/google/cloud/talent_v4/proto/company_service.proto
deleted file mode 100644
index 54ee4800..00000000
--- a/google/cloud/talent_v4/proto/company_service.proto
+++ /dev/null
@@ -1,187 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4/common.proto";
-import "google/cloud/talent/v4/company.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CompanyServiceProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A service that handles company management, including CRUD and enumeration.
-service CompanyService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Creates a new company entity.
- rpc CreateCompany(CreateCompanyRequest) returns (Company) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/companies"
- body: "company"
- };
- option (google.api.method_signature) = "parent,company";
- }
-
- // Retrieves specified company.
- rpc GetCompany(GetCompanyRequest) returns (Company) {
- option (google.api.http) = {
- get: "/v4/{name=projects/*/tenants/*/companies/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates specified company.
- rpc UpdateCompany(UpdateCompanyRequest) returns (Company) {
- option (google.api.http) = {
- patch: "/v4/{company.name=projects/*/tenants/*/companies/*}"
- body: "company"
- };
- option (google.api.method_signature) = "company,update_mask";
- }
-
- // Deletes specified company.
- // Prerequisite: The company has no jobs associated with it.
- rpc DeleteCompany(DeleteCompanyRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4/{name=projects/*/tenants/*/companies/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Lists all companies associated with the project.
- rpc ListCompanies(ListCompaniesRequest) returns (ListCompaniesResponse) {
- option (google.api.http) = {
- get: "/v4/{parent=projects/*/tenants/*}/companies"
- };
- option (google.api.method_signature) = "parent";
- }
-}
-
-// The Request of the CreateCompany method.
-message CreateCompanyRequest {
- // Required. Resource name of the tenant under which the company is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-
- // Required. The company to be created.
- Company company = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Request for getting a company by name.
-message GetCompanyRequest {
- // Required. The resource name of the company to be retrieved.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/api-test-project/tenants/foo/companies/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }
- ];
-}
-
-// Request for updating a specified company.
-message UpdateCompanyRequest {
- // Required. The company resource to replace the current resource in the system.
- Company company = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // If [update_mask][google.cloud.talent.v4.UpdateCompanyRequest.update_mask] is provided, only the specified fields in
- // [company][google.cloud.talent.v4.UpdateCompanyRequest.company] are updated. Otherwise all the fields are updated.
- //
- // A field mask to specify the company fields to be updated. Only
- // top level fields of [Company][google.cloud.talent.v4.Company] are supported.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Request to delete a company.
-message DeleteCompanyRequest {
- // Required. The resource name of the company to be deleted.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/foo/tenants/bar/companies/baz".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }
- ];
-}
-
-// List companies for which the client has ACL visibility.
-message ListCompaniesRequest {
- // Required. Resource name of the tenant under which the company is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-
- // The starting indicator from which to return results.
- string page_token = 2;
-
- // The maximum number of companies to be returned, at most 100.
- // Default is 100 if a non-positive number is provided.
- int32 page_size = 3;
-
- // Set to true if the companies requested must have open jobs.
- //
- // Defaults to false.
- //
- // If true, at most [page_size][google.cloud.talent.v4.ListCompaniesRequest.page_size] of companies are fetched, among which
- // only those with open jobs are returned.
- bool require_open_jobs = 4;
-}
-
-// The List companies response object.
-message ListCompaniesResponse {
- // Companies for the current client.
- repeated Company companies = 1;
-
- // A token to retrieve the next page of results.
- string next_page_token = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-}
diff --git a/google/cloud/talent_v4/proto/completion_service.proto b/google/cloud/talent_v4/proto/completion_service.proto
deleted file mode 100644
index 73af1e87..00000000
--- a/google/cloud/talent_v4/proto/completion_service.proto
+++ /dev/null
@@ -1,154 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/annotations.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4/common.proto";
-import "google/api/client.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CompletionServiceProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A service handles auto completion.
-service Completion {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Completes the specified prefix with keyword suggestions.
- // Intended for use by a job search auto-complete search box.
- rpc CompleteQuery(CompleteQueryRequest) returns (CompleteQueryResponse) {
- option (google.api.http) = {
- get: "/v4/{tenant=projects/*/tenants/*}:completeQuery"
- };
- }
-}
-
-// Auto-complete parameters.
-message CompleteQueryRequest {
- // Enum to specify the scope of completion.
- enum CompletionScope {
- // Default value.
- COMPLETION_SCOPE_UNSPECIFIED = 0;
-
- // Suggestions are based only on the data provided by the client.
- TENANT = 1;
-
- // Suggestions are based on all jobs data in the system that's visible to
- // the client
- PUBLIC = 2;
- }
-
- // Enum to specify auto-completion topics.
- enum CompletionType {
- // Default value.
- COMPLETION_TYPE_UNSPECIFIED = 0;
-
- // Suggest job titles for jobs autocomplete.
- //
- // For [CompletionType.JOB_TITLE][google.cloud.talent.v4.CompleteQueryRequest.CompletionType.JOB_TITLE] type, only open jobs with the same
- // [language_codes][google.cloud.talent.v4.CompleteQueryRequest.language_codes] are returned.
- JOB_TITLE = 1;
-
- // Suggest company names for jobs autocomplete.
- //
- // For [CompletionType.COMPANY_NAME][google.cloud.talent.v4.CompleteQueryRequest.CompletionType.COMPANY_NAME] type,
- // only companies having open jobs with the same [language_codes][google.cloud.talent.v4.CompleteQueryRequest.language_codes] are
- // returned.
- COMPANY_NAME = 2;
-
- // Suggest both job titles and company names for jobs autocomplete.
- //
- // For [CompletionType.COMBINED][google.cloud.talent.v4.CompleteQueryRequest.CompletionType.COMBINED] type, only open jobs with the same
- // [language_codes][google.cloud.talent.v4.CompleteQueryRequest.language_codes] or companies having open jobs with the same
- // [language_codes][google.cloud.talent.v4.CompleteQueryRequest.language_codes] are returned.
- COMBINED = 3;
- }
-
- // Required. Resource name of tenant the completion is performed within.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string tenant = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-
- // Required. The query used to generate suggestions.
- //
- // The maximum number of allowed characters is 255.
- string query = 2 [(google.api.field_behavior) = REQUIRED];
-
- // The list of languages of the query. This is
- // the BCP-47 language code, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47).
- //
- // The maximum number of allowed characters is 255.
- repeated string language_codes = 3;
-
- // Required. Completion result count.
- //
- // The maximum allowed page size is 10.
- int32 page_size = 4 [(google.api.field_behavior) = REQUIRED];
-
- // If provided, restricts completion to specified company.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/foo/tenants/bar/companies/baz".
- string company = 5 [(google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }];
-
- // The scope of the completion. The defaults is [CompletionScope.PUBLIC][google.cloud.talent.v4.CompleteQueryRequest.CompletionScope.PUBLIC].
- CompletionScope scope = 6;
-
- // The completion topic. The default is [CompletionType.COMBINED][google.cloud.talent.v4.CompleteQueryRequest.CompletionType.COMBINED].
- CompletionType type = 7;
-}
-
-// Response of auto-complete query.
-message CompleteQueryResponse {
- // Resource that represents completion results.
- message CompletionResult {
- // The suggestion for the query.
- string suggestion = 1;
-
- // The completion topic.
- CompleteQueryRequest.CompletionType type = 2;
-
- // The URI of the company image for
- // [COMPANY_NAME][google.cloud.talent.v4.CompleteQueryRequest.CompletionType.COMPANY_NAME].
- string image_uri = 3;
- }
-
- // Results of the matching job/company candidates.
- repeated CompletionResult completion_results = 1;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 2;
-}
diff --git a/google/cloud/talent_v4/proto/event.proto b/google/cloud/talent_v4/proto/event.proto
deleted file mode 100644
index 874228e1..00000000
--- a/google/cloud/talent_v4/proto/event.proto
+++ /dev/null
@@ -1,171 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/field_behavior.proto";
-import "google/protobuf/timestamp.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "EventProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// An event issued when an end user interacts with the application that
-// implements Cloud Talent Solution. Providing this information improves the
-// quality of results for the API clients, enabling the
-// service to perform optimally. The number of events sent must be consistent
-// with other calls, such as job searches, issued to the service by the client.
-message ClientEvent {
- // Strongly recommended for the best service experience.
- //
- // A unique ID generated in the API responses. It can be found in
- // [ResponseMetadata.request_id][google.cloud.talent.v4.ResponseMetadata.request_id].
- string request_id = 1;
-
- // Required. A unique identifier, generated by the client application.
- string event_id = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The timestamp of the event.
- google.protobuf.Timestamp create_time = 4 [(google.api.field_behavior) = REQUIRED];
-
- // Required.
- //
- // The detail information of a specific event type.
- oneof event {
- // An event issued when a job seeker interacts with the application that
- // implements Cloud Talent Solution.
- JobEvent job_event = 5;
- }
-
- // Notes about the event provided by recruiters or other users, for example,
- // feedback on why a job was bookmarked.
- string event_notes = 9;
-}
-
-// An event issued when a job seeker interacts with the application that
-// implements Cloud Talent Solution.
-message JobEvent {
- // An enumeration of an event attributed to the behavior of the end user,
- // such as a job seeker.
- enum JobEventType {
- // The event is unspecified by other provided values.
- JOB_EVENT_TYPE_UNSPECIFIED = 0;
-
- // The job seeker or other entity interacting with the service has
- // had a job rendered in their view, such as in a list of search results in
- // a compressed or clipped format. This event is typically associated with
- // the viewing of a jobs list on a single page by a job seeker.
- IMPRESSION = 1;
-
- // The job seeker, or other entity interacting with the service, has
- // viewed the details of a job, including the full description. This
- // event doesn't apply to the viewing a snippet of a job appearing as a
- // part of the job search results. Viewing a snippet is associated with an
- // [impression][google.cloud.talent.v4.JobEvent.JobEventType.IMPRESSION]).
- VIEW = 2;
-
- // The job seeker or other entity interacting with the service
- // performed an action to view a job and was redirected to a different
- // website for job.
- VIEW_REDIRECT = 3;
-
- // The job seeker or other entity interacting with the service
- // began the process or demonstrated the intention of applying for a job.
- APPLICATION_START = 4;
-
- // The job seeker or other entity interacting with the service
- // submitted an application for a job.
- APPLICATION_FINISH = 5;
-
- // The job seeker or other entity interacting with the service
- // submitted an application for a job with a single click without
- // entering information. If a job seeker performs this action, send only
- // this event to the service. Do not also send
- // [JobEventType.APPLICATION_START][google.cloud.talent.v4.JobEvent.JobEventType.APPLICATION_START] or [JobEventType.APPLICATION_FINISH][google.cloud.talent.v4.JobEvent.JobEventType.APPLICATION_FINISH]
- // events.
- APPLICATION_QUICK_SUBMISSION = 6;
-
- // The job seeker or other entity interacting with the service
- // performed an action to apply to a job and was redirected to a different
- // website to complete the application.
- APPLICATION_REDIRECT = 7;
-
- // The job seeker or other entity interacting with the service began the
- // process or demonstrated the intention of applying for a job from the
- // search results page without viewing the details of the job posting.
- // If sending this event, JobEventType.VIEW event shouldn't be sent.
- APPLICATION_START_FROM_SEARCH = 8;
-
- // The job seeker, or other entity interacting with the service, performs an
- // action with a single click from the search results page to apply to a job
- // (without viewing the details of the job posting), and is redirected
- // to a different website to complete the application. If a candidate
- // performs this action, send only this event to the service. Do not also
- // send [JobEventType.APPLICATION_START][google.cloud.talent.v4.JobEvent.JobEventType.APPLICATION_START],
- // [JobEventType.APPLICATION_FINISH][google.cloud.talent.v4.JobEvent.JobEventType.APPLICATION_FINISH] or [JobEventType.VIEW][google.cloud.talent.v4.JobEvent.JobEventType.VIEW] events.
- APPLICATION_REDIRECT_FROM_SEARCH = 9;
-
- // This event should be used when a company submits an application
- // on behalf of a job seeker. This event is intended for use by staffing
- // agencies attempting to place candidates.
- APPLICATION_COMPANY_SUBMIT = 10;
-
- // The job seeker or other entity interacting with the service demonstrated
- // an interest in a job by bookmarking or saving it.
- BOOKMARK = 11;
-
- // The job seeker or other entity interacting with the service was
- // sent a notification, such as an email alert or device notification,
- // containing one or more jobs listings generated by the service.
- NOTIFICATION = 12;
-
- // The job seeker or other entity interacting with the service was
- // employed by the hiring entity (employer). Send this event
- // only if the job seeker was hired through an application that was
- // initiated by a search conducted through the Cloud Talent Solution
- // service.
- HIRED = 13;
-
- // A recruiter or staffing agency submitted an application on behalf of the
- // candidate after interacting with the service to identify a suitable job
- // posting.
- SENT_CV = 14;
-
- // The entity interacting with the service (for example, the job seeker),
- // was granted an initial interview by the hiring entity (employer). This
- // event should only be sent if the job seeker was granted an interview as
- // part of an application that was initiated by a search conducted through /
- // recommendation provided by the Cloud Talent Solution service.
- INTERVIEW_GRANTED = 15;
- }
-
- // Required. The type of the event (see [JobEventType][google.cloud.talent.v4.JobEvent.JobEventType]).
- JobEventType type = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The [job name(s)][google.cloud.talent.v4.Job.name] associated with this event.
- // For example, if this is an [impression][google.cloud.talent.v4.JobEvent.JobEventType.IMPRESSION] event,
- // this field contains the identifiers of all jobs shown to the job seeker.
- // If this was a [view][google.cloud.talent.v4.JobEvent.JobEventType.VIEW] event, this field contains the
- // identifier of the viewed job.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}", for
- // example, "projects/foo/tenants/bar/jobs/baz".
- repeated string jobs = 2 [(google.api.field_behavior) = REQUIRED];
-}
diff --git a/google/cloud/talent_v4/proto/event_service.proto b/google/cloud/talent_v4/proto/event_service.proto
deleted file mode 100644
index 0f181367..00000000
--- a/google/cloud/talent_v4/proto/event_service.proto
+++ /dev/null
@@ -1,70 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4/event.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "EventServiceProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A service handles client event report.
-service EventService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Report events issued when end user interacts with customer's application
- // that uses Cloud Talent Solution. You may inspect the created events in
- // [self service
- // tools](https://console.cloud.google.com/talent-solution/overview).
- // [Learn
- // more](https://cloud.google.com/talent-solution/docs/management-tools)
- // about self service tools.
- rpc CreateClientEvent(CreateClientEventRequest) returns (ClientEvent) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/clientEvents"
- body: "client_event"
- };
- option (google.api.method_signature) = "parent,client_event";
- }
-}
-
-// The report event request.
-message CreateClientEventRequest {
- // Required. Resource name of the tenant under which the event is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-
- // Required. Events issued when end user interacts with customer's application that
- // uses Cloud Talent Solution.
- ClientEvent client_event = 2 [(google.api.field_behavior) = REQUIRED];
-}
diff --git a/google/cloud/talent_v4/proto/filters.proto b/google/cloud/talent_v4/proto/filters.proto
deleted file mode 100644
index a0063cab..00000000
--- a/google/cloud/talent_v4/proto/filters.proto
+++ /dev/null
@@ -1,338 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/field_behavior.proto";
-import "google/cloud/talent/v4/common.proto";
-import "google/protobuf/duration.proto";
-import "google/type/latlng.proto";
-import "google/type/timeofday.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "FiltersProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// The query required to perform a search query.
-message JobQuery {
- // The query string that matches against the job title, description, and
- // location fields.
- //
- // The maximum number of allowed characters is 255.
- string query = 1;
-
- // The language code of [query][google.cloud.talent.v4.JobQuery.query]. For example, "en-US". This field helps to
- // better interpret the query.
- //
- // If a value isn't specified, the query language code is automatically
- // detected, which may not be accurate.
- //
- // Language code should be in BCP-47 format, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47).
- string query_language_code = 14;
-
- // This filter specifies the company entities to search against.
- //
- // If a value isn't specified, jobs are searched for against all
- // companies.
- //
- // If multiple values are specified, jobs are searched against the
- // companies specified.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}". For
- // example, "projects/foo/tenants/bar/companies/baz".
- //
- // At most 20 company filters are allowed.
- repeated string companies = 2;
-
- // The location filter specifies geo-regions containing the jobs to
- // search against. See [LocationFilter][google.cloud.talent.v4.LocationFilter] for more information.
- //
- // If a location value isn't specified, jobs fitting the other search
- // criteria are retrieved regardless of where they're located.
- //
- // If multiple values are specified, jobs are retrieved from any of the
- // specified locations. If different values are specified for the
- // [LocationFilter.distance_in_miles][google.cloud.talent.v4.LocationFilter.distance_in_miles] parameter, the maximum provided
- // distance is used for all locations.
- //
- // At most 5 location filters are allowed.
- repeated LocationFilter location_filters = 3;
-
- // The category filter specifies the categories of jobs to search against.
- // See [JobCategory][google.cloud.talent.v4.JobCategory] for more information.
- //
- // If a value isn't specified, jobs from any category are searched against.
- //
- // If multiple values are specified, jobs from any of the specified
- // categories are searched against.
- repeated JobCategory job_categories = 4;
-
- // Allows filtering jobs by commute time with different travel methods (for
- // example, driving or public transit).
- //
- // Note: This only works when you specify a [CommuteMethod][google.cloud.talent.v4.CommuteMethod]. In this case,
- // [location_filters][google.cloud.talent.v4.JobQuery.location_filters] is ignored.
- //
- // Currently we don't support sorting by commute time.
- CommuteFilter commute_filter = 5;
-
- // This filter specifies the exact company [Company.display_name][google.cloud.talent.v4.Company.display_name]
- // of the jobs to search against.
- //
- // If a value isn't specified, jobs within the search results are
- // associated with any company.
- //
- // If multiple values are specified, jobs within the search results may be
- // associated with any of the specified companies.
- //
- // At most 20 company display name filters are allowed.
- repeated string company_display_names = 6;
-
- // This search filter is applied only to
- // [Job.compensation_info][google.cloud.talent.v4.Job.compensation_info]. For example, if the filter is specified
- // as "Hourly job with per-hour compensation > $15", only jobs meeting
- // these criteria are searched. If a filter isn't defined, all open jobs
- // are searched.
- CompensationFilter compensation_filter = 7;
-
- // This filter specifies a structured syntax to match against the
- // [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes] marked as `filterable`.
- //
- // The syntax for this expression is a subset of SQL syntax.
- //
- // Supported operators are: `=`, `!=`, `<`, `<=`, `>`, and `>=` where the
- // left of the operator is a custom field key and the right of the operator
- // is a number or a quoted string. You must escape backslash (\\) and
- // quote (\") characters.
- //
- // Supported functions are `LOWER([field_name])` to
- // perform a case insensitive match and `EMPTY([field_name])` to filter on the
- // existence of a key.
- //
- // Boolean expressions (AND/OR/NOT) are supported up to 3 levels of
- // nesting (for example, "((A AND B AND C) OR NOT D) AND E"), a maximum of 100
- // comparisons or functions are allowed in the expression. The expression
- // must be < 6000 bytes in length.
- //
- // Sample Query:
- // `(LOWER(driving_license)="class \"a\"" OR EMPTY(driving_license)) AND
- // driving_years > 10`
- string custom_attribute_filter = 8;
-
- // This flag controls the spell-check feature. If false, the
- // service attempts to correct a misspelled query,
- // for example, "enginee" is corrected to "engineer".
- //
- // Defaults to false: a spell check is performed.
- bool disable_spell_check = 9;
-
- // The employment type filter specifies the employment type of jobs to
- // search against, such as [EmploymentType.FULL_TIME][google.cloud.talent.v4.EmploymentType.FULL_TIME].
- //
- // If a value isn't specified, jobs in the search results includes any
- // employment type.
- //
- // If multiple values are specified, jobs in the search results include
- // any of the specified employment types.
- repeated EmploymentType employment_types = 10;
-
- // This filter specifies the locale of jobs to search against,
- // for example, "en-US".
- //
- // If a value isn't specified, the search results can contain jobs in any
- // locale.
- //
- //
- // Language codes should be in BCP-47 format, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47).
- //
- // At most 10 language code filters are allowed.
- repeated string language_codes = 11;
-
- // Jobs published within a range specified by this filter are searched
- // against.
- TimestampRange publish_time_range = 12;
-
- // This filter specifies a list of job names to be excluded during search.
- //
- // At most 400 excluded job names are allowed.
- repeated string excluded_jobs = 13;
-}
-
-// Geographic region of the search.
-message LocationFilter {
- // Specify whether to include telecommute jobs.
- enum TelecommutePreference {
- // Default value if the telecommute preference isn't specified.
- TELECOMMUTE_PREFERENCE_UNSPECIFIED = 0;
-
- // Exclude telecommute jobs.
- TELECOMMUTE_EXCLUDED = 1;
-
- // Allow telecommute jobs.
- TELECOMMUTE_ALLOWED = 2;
- }
-
- // The address name, such as "Mountain View" or "Bay Area".
- string address = 1;
-
- // CLDR region code of the country/region of the address. This is used
- // to address ambiguity of the user-input location, for example, "Liverpool"
- // against "Liverpool, NY, US" or "Liverpool, UK".
- //
- // Set this field to bias location resolution toward a specific country
- // or territory. If this field is not set, application behavior is biased
- // toward the United States by default.
- //
- // See
- // https://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
- // for details. Example: "CH" for Switzerland.
- string region_code = 2;
-
- // The latitude and longitude of the geographic center to search from. This
- // field is ignored if `address` is provided.
- google.type.LatLng lat_lng = 3;
-
- // The distance_in_miles is applied when the location being searched for is
- // identified as a city or smaller. This field is ignored if the location
- // being searched for is a state or larger.
- double distance_in_miles = 4;
-
- // Allows the client to return jobs without a
- // set location, specifically, telecommuting jobs (telecommuting is considered
- // by the service as a special location.
- // [Job.posting_region][google.cloud.talent.v4.Job.posting_region] indicates if a job permits telecommuting.
- // If this field is set to [TelecommutePreference.TELECOMMUTE_ALLOWED][google.cloud.talent.v4.LocationFilter.TelecommutePreference.TELECOMMUTE_ALLOWED],
- // telecommuting jobs are searched, and [address][google.cloud.talent.v4.LocationFilter.address] and [lat_lng][google.cloud.talent.v4.LocationFilter.lat_lng] are
- // ignored. If not set or set to
- // [TelecommutePreference.TELECOMMUTE_EXCLUDED][google.cloud.talent.v4.LocationFilter.TelecommutePreference.TELECOMMUTE_EXCLUDED], telecommute job are not
- // searched.
- //
- // This filter can be used by itself to search exclusively for telecommuting
- // jobs, or it can be combined with another location
- // filter to search for a combination of job locations,
- // such as "Mountain View" or "telecommuting" jobs. However, when used in
- // combination with other location filters, telecommuting jobs can be
- // treated as less relevant than other jobs in the search response.
- //
- // This field is only used for job search requests.
- TelecommutePreference telecommute_preference = 5;
-}
-
-// Filter on job compensation type and amount.
-message CompensationFilter {
- // Specify the type of filtering.
- enum FilterType {
- // Filter type unspecified. Position holder, INVALID, should never be used.
- FILTER_TYPE_UNSPECIFIED = 0;
-
- // Filter by `base compensation entry's` unit. A job is a match if and
- // only if the job contains a base CompensationEntry and the base
- // CompensationEntry's unit matches provided [units][google.cloud.talent.v4.CompensationFilter.units].
- // Populate one or more [units][google.cloud.talent.v4.CompensationFilter.units].
- //
- // See [CompensationInfo.CompensationEntry][google.cloud.talent.v4.CompensationInfo.CompensationEntry] for definition of
- // base compensation entry.
- UNIT_ONLY = 1;
-
- // Filter by `base compensation entry's` unit and amount / range. A job
- // is a match if and only if the job contains a base CompensationEntry, and
- // the base entry's unit matches provided
- // [CompensationUnit][google.cloud.talent.v4.CompensationInfo.CompensationUnit] and
- // amount or range overlaps with provided
- // [CompensationRange][google.cloud.talent.v4.CompensationInfo.CompensationRange].
- //
- // See [CompensationInfo.CompensationEntry][google.cloud.talent.v4.CompensationInfo.CompensationEntry] for definition of
- // base compensation entry.
- //
- // Set exactly one [units][google.cloud.talent.v4.CompensationFilter.units] and populate [range][google.cloud.talent.v4.CompensationFilter.range].
- UNIT_AND_AMOUNT = 2;
-
- // Filter by annualized base compensation amount and `base compensation
- // entry's` unit. Populate [range][google.cloud.talent.v4.CompensationFilter.range] and zero or more [units][google.cloud.talent.v4.CompensationFilter.units].
- ANNUALIZED_BASE_AMOUNT = 3;
-
- // Filter by annualized total compensation amount and `base compensation
- // entry's` unit . Populate [range][google.cloud.talent.v4.CompensationFilter.range] and zero or more [units][google.cloud.talent.v4.CompensationFilter.units].
- ANNUALIZED_TOTAL_AMOUNT = 4;
- }
-
- // Required. Type of filter.
- FilterType type = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. Specify desired `base compensation entry's`
- // [CompensationInfo.CompensationUnit][google.cloud.talent.v4.CompensationInfo.CompensationUnit].
- repeated CompensationInfo.CompensationUnit units = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Compensation range.
- CompensationInfo.CompensationRange range = 3;
-
- // If set to true, jobs with unspecified compensation range fields are
- // included.
- bool include_jobs_with_unspecified_compensation_range = 4;
-}
-
-// Parameters needed for commute search.
-message CommuteFilter {
- // The traffic density to use when calculating commute time.
- enum RoadTraffic {
- // Road traffic situation isn't specified.
- ROAD_TRAFFIC_UNSPECIFIED = 0;
-
- // Optimal commute time without considering any traffic impact.
- TRAFFIC_FREE = 1;
-
- // Commute time calculation takes in account the peak traffic impact.
- BUSY_HOUR = 2;
- }
-
- // Required. The method of transportation to calculate the commute time for.
- CommuteMethod commute_method = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The latitude and longitude of the location to calculate the
- // commute time from.
- google.type.LatLng start_coordinates = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The maximum travel time in seconds. The maximum allowed value is `3600s`
- // (one hour). Format is `123s`.
- google.protobuf.Duration travel_duration = 3 [(google.api.field_behavior) = REQUIRED];
-
- // If `true`, jobs without street level addresses may also be returned.
- // For city level addresses, the city center is used. For state and coarser
- // level addresses, text matching is used.
- // If this field is set to `false` or isn't specified, only jobs that include
- // street level addresses will be returned by commute search.
- bool allow_imprecise_addresses = 4;
-
- // Traffic factor to take into account while searching by commute.
- oneof traffic_option {
- // Specifies the traffic density to use when calculating commute time.
- RoadTraffic road_traffic = 5;
-
- // The departure time used to calculate traffic impact, represented as
- // [google.type.TimeOfDay][google.type.TimeOfDay] in local time zone.
- //
- // Currently traffic model is restricted to hour level resolution.
- google.type.TimeOfDay departure_time = 6;
- }
-}
diff --git a/google/cloud/talent_v4/proto/histogram.proto b/google/cloud/talent_v4/proto/histogram.proto
deleted file mode 100644
index df4fbbb4..00000000
--- a/google/cloud/talent_v4/proto/histogram.proto
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "HistogramProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// The histogram request.
-message HistogramQuery {
- // An expression specifies a histogram request against matching jobs for
- // searches.
- //
- // See [SearchJobsRequest.histogram_queries][google.cloud.talent.v4.SearchJobsRequest.histogram_queries] for details about syntax.
- string histogram_query = 1;
-}
-
-// Histogram result that matches [HistogramQuery][google.cloud.talent.v4.HistogramQuery] specified in searches.
-message HistogramQueryResult {
- // Requested histogram expression.
- string histogram_query = 1;
-
- // A map from the values of the facet associated with distinct values to the
- // number of matching entries with corresponding value.
- //
- // The key format is:
- //
- // * (for string histogram) string values stored in the field.
- // * (for named numeric bucket) name specified in `bucket()` function, like
- // for `bucket(0, MAX, "non-negative")`, the key will be `non-negative`.
- // * (for anonymous numeric bucket) range formatted as `-`, for
- // example, `0-1000`, `MIN-0`, and `0-MAX`.
- map histogram = 2;
-}
diff --git a/google/cloud/talent_v4/proto/job.proto b/google/cloud/talent_v4/proto/job.proto
deleted file mode 100644
index 4c24f430..00000000
--- a/google/cloud/talent_v4/proto/job.proto
+++ /dev/null
@@ -1,342 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4/common.proto";
-import "google/protobuf/timestamp.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "JobProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A Job resource represents a job posting (also referred to as a "job listing"
-// or "job requisition"). A job belongs to a [Company][google.cloud.talent.v4.Company], which is the hiring
-// entity responsible for the job.
-message Job {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Job"
- pattern: "projects/{project}/tenants/{tenant}/jobs/{job}"
- };
-
- // Application related details of a job posting.
- message ApplicationInfo {
- // Use this field to specify email address(es) to which resumes or
- // applications can be sent.
- //
- // The maximum number of allowed characters for each entry is 255.
- repeated string emails = 1;
-
- // Use this field to provide instructions, such as "Mail your application
- // to ...", that a candidate can follow to apply for the job.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 3,000.
- string instruction = 2;
-
- // Use this URI field to direct an applicant to a website, for example to
- // link to an online application form.
- //
- // The maximum number of allowed characters for each entry is 2,000.
- repeated string uris = 3;
- }
-
- // Derived details about the job posting.
- message DerivedInfo {
- // Structured locations of the job, resolved from [Job.addresses][google.cloud.talent.v4.Job.addresses].
- //
- // [locations][google.cloud.talent.v4.Job.DerivedInfo.locations] are exactly matched to [Job.addresses][google.cloud.talent.v4.Job.addresses] in the same
- // order.
- repeated Location locations = 1;
-
- // Job categories derived from [Job.title][google.cloud.talent.v4.Job.title] and [Job.description][google.cloud.talent.v4.Job.description].
- repeated JobCategory job_categories = 3;
- }
-
- // Options for job processing.
- message ProcessingOptions {
- // If set to `true`, the service does not attempt to resolve a
- // more precise address for the job.
- bool disable_street_address_resolution = 1;
-
- // Option for job HTML content sanitization. Applied fields are:
- //
- // * description
- // * applicationInfo.instruction
- // * incentives
- // * qualifications
- // * responsibilities
- //
- // HTML tags in these fields may be stripped if sanitiazation isn't
- // disabled.
- //
- // Defaults to [HtmlSanitization.SIMPLE_FORMATTING_ONLY][google.cloud.talent.v4.HtmlSanitization.SIMPLE_FORMATTING_ONLY].
- HtmlSanitization html_sanitization = 2;
- }
-
- // Required during job update.
- //
- // The resource name for the job. This is generated by the service when a
- // job is created.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}". For
- // example, "projects/foo/tenants/bar/jobs/baz".
- //
- // Use of this field in job queries and API calls is preferred over the use of
- // [requisition_id][google.cloud.talent.v4.Job.requisition_id] since this value is unique.
- string name = 1;
-
- // Required. The resource name of the company listing the job.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}". For
- // example, "projects/foo/tenants/bar/companies/baz".
- string company = 2 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }
- ];
-
- // Required. The requisition ID, also referred to as the posting ID, is assigned by the
- // client to identify a job. This field is intended to be used by clients
- // for client identification and tracking of postings. A job isn't allowed
- // to be created if there is another job with the same [company][google.cloud.talent.v4.Job.name],
- // [language_code][google.cloud.talent.v4.Job.language_code] and [requisition_id][google.cloud.talent.v4.Job.requisition_id].
- //
- // The maximum number of allowed characters is 255.
- string requisition_id = 3 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The title of the job, such as "Software Engineer"
- //
- // The maximum number of allowed characters is 500.
- string title = 4 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The description of the job, which typically includes a multi-paragraph
- // description of the company and related information. Separate fields are
- // provided on the job object for [responsibilities][google.cloud.talent.v4.Job.responsibilities],
- // [qualifications][google.cloud.talent.v4.Job.qualifications], and other job characteristics. Use of
- // these separate job fields is recommended.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 100,000.
- string description = 5 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // Location(s) where the employer is looking to hire for this job posting.
- //
- // Specifying the full street address(es) of the hiring location enables
- // better API results, especially job searches by commute time.
- //
- // At most 50 locations are allowed for best search performance. If a job has
- // more locations, it is suggested to split it into multiple jobs with unique
- // [requisition_id][google.cloud.talent.v4.Job.requisition_id]s (e.g. 'ReqA' becomes 'ReqA-1', 'ReqA-2', and so on.) as
- // multiple jobs with the same [company][google.cloud.talent.v4.Job.company], [language_code][google.cloud.talent.v4.Job.language_code] and
- // [requisition_id][google.cloud.talent.v4.Job.requisition_id] are not allowed. If the original [requisition_id][google.cloud.talent.v4.Job.requisition_id] must
- // be preserved, a custom field should be used for storage. It is also
- // suggested to group the locations that close to each other in the same job
- // for better search experience.
- //
- // The maximum number of allowed characters is 500.
- repeated string addresses = 6;
-
- // Job application information.
- ApplicationInfo application_info = 7;
-
- // The benefits included with the job.
- repeated JobBenefit job_benefits = 8;
-
- // Job compensation information (a.k.a. "pay rate") i.e., the compensation
- // that will paid to the employee.
- CompensationInfo compensation_info = 9;
-
- // A map of fields to hold both filterable and non-filterable custom job
- // attributes that are not covered by the provided structured fields.
- //
- // The keys of the map are strings up to 64 bytes and must match the
- // pattern: [a-zA-Z][a-zA-Z0-9_]*. For example, key0LikeThis or
- // KEY_1_LIKE_THIS.
- //
- // At most 100 filterable and at most 100 unfilterable keys are supported.
- // For filterable `string_values`, across all keys at most 200 values are
- // allowed, with each string no more than 255 characters. For unfilterable
- // `string_values`, the maximum total size of `string_values` across all keys
- // is 50KB.
- map custom_attributes = 10;
-
- // The desired education degrees for the job, such as Bachelors, Masters.
- repeated DegreeType degree_types = 11;
-
- // The department or functional area within the company with the open
- // position.
- //
- // The maximum number of allowed characters is 255.
- string department = 12;
-
- // The employment type(s) of a job, for example,
- // [full time][google.cloud.talent.v4.EmploymentType.FULL_TIME] or
- // [part time][google.cloud.talent.v4.EmploymentType.PART_TIME].
- repeated EmploymentType employment_types = 13;
-
- // A description of bonus, commission, and other compensation
- // incentives associated with the job not including salary or pay.
- //
- // The maximum number of allowed characters is 10,000.
- string incentives = 14;
-
- // The language of the posting. This field is distinct from
- // any requirements for fluency that are associated with the job.
- //
- // Language codes must be in BCP-47 format, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47){:
- // class="external" target="_blank" }.
- //
- // If this field is unspecified and [Job.description][google.cloud.talent.v4.Job.description] is present, detected
- // language code based on [Job.description][google.cloud.talent.v4.Job.description] is assigned, otherwise
- // defaults to 'en_US'.
- string language_code = 15;
-
- // The experience level associated with the job, such as "Entry Level".
- JobLevel job_level = 16;
-
- // A promotion value of the job, as determined by the client.
- // The value determines the sort order of the jobs returned when searching for
- // jobs using the featured jobs search call, with higher promotional values
- // being returned first and ties being resolved by relevance sort. Only the
- // jobs with a promotionValue >0 are returned in a FEATURED_JOB_SEARCH.
- //
- // Default value is 0, and negative values are treated as 0.
- int32 promotion_value = 17;
-
- // A description of the qualifications required to perform the
- // job. The use of this field is recommended
- // as an alternative to using the more general [description][google.cloud.talent.v4.Job.description] field.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 10,000.
- string qualifications = 18;
-
- // A description of job responsibilities. The use of this field is
- // recommended as an alternative to using the more general [description][google.cloud.talent.v4.Job.description]
- // field.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 10,000.
- string responsibilities = 19;
-
- // The job [PostingRegion][google.cloud.talent.v4.PostingRegion] (for example, state, country) throughout
- // which the job is available. If this field is set, a [LocationFilter][google.cloud.talent.v4.LocationFilter]
- // in a search query within the job region finds this job posting if an
- // exact location match isn't specified. If this field is set to
- // [PostingRegion.NATION][google.cloud.talent.v4.PostingRegion.NATION] or [PostingRegion.ADMINISTRATIVE_AREA][google.cloud.talent.v4.PostingRegion.ADMINISTRATIVE_AREA],
- // setting job [Job.addresses][google.cloud.talent.v4.Job.addresses] to the same location level as this field
- // is strongly recommended.
- PostingRegion posting_region = 20;
-
- // Deprecated. The job is only visible to the owner.
- //
- // The visibility of the job.
- //
- // Defaults to [Visibility.ACCOUNT_ONLY][google.cloud.talent.v4.Visibility.ACCOUNT_ONLY] if not specified.
- Visibility visibility = 21 [deprecated = true];
-
- // The start timestamp of the job in UTC time zone. Typically this field
- // is used for contracting engagements. Invalid timestamps are ignored.
- google.protobuf.Timestamp job_start_time = 22;
-
- // The end timestamp of the job. Typically this field is used for contracting
- // engagements. Invalid timestamps are ignored.
- google.protobuf.Timestamp job_end_time = 23;
-
- // The timestamp this job posting was most recently published. The default
- // value is the time the request arrives at the server. Invalid timestamps are
- // ignored.
- google.protobuf.Timestamp posting_publish_time = 24;
-
- // Strongly recommended for the best service experience.
- //
- // The expiration timestamp of the job. After this timestamp, the
- // job is marked as expired, and it no longer appears in search results. The
- // expired job can't be listed by the [ListJobs][google.cloud.talent.v4.JobService.ListJobs] API,
- // but it can be retrieved with the [GetJob][google.cloud.talent.v4.JobService.GetJob] API or
- // updated with the [UpdateJob][google.cloud.talent.v4.JobService.UpdateJob] API or deleted with
- // the [DeleteJob][google.cloud.talent.v4.JobService.DeleteJob] API. An expired job can
- // be updated and opened again by using a future expiration timestamp.
- // Updating an expired job fails if there is another existing open job with
- // same [company][google.cloud.talent.v4.Job.company], [language_code][google.cloud.talent.v4.Job.language_code] and [requisition_id][google.cloud.talent.v4.Job.requisition_id].
- //
- // The expired jobs are retained in our system for 90 days. However, the
- // overall expired job count cannot exceed 3 times the maximum number of
- // open jobs over previous 7 days. If this threshold is exceeded,
- // expired jobs are cleaned out in order of earliest expire time.
- // Expired jobs are no longer accessible after they are cleaned
- // out.
- //
- // Invalid timestamps are ignored, and treated as expire time not provided.
- //
- // If the timestamp is before the instant request is made, the job
- // is treated as expired immediately on creation. This kind of job can
- // not be updated. And when creating a job with past timestamp, the
- // [posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] must be set before
- // [posting_expire_time][google.cloud.talent.v4.Job.posting_expire_time]. The purpose of this feature is
- // to allow other objects, such as [Application][], to refer a job
- // that didn't exist in the system prior to becoming expired. If you
- // want to modify a job that was expired on creation,
- // delete it and create a new one.
- //
- // If this value isn't provided at the time of job creation or is invalid,
- // the job posting expires after 30 days from the job's creation time. For
- // example, if the job was created on 2017/01/01 13:00AM UTC with an
- // unspecified expiration date, the job expires after 2017/01/31 13:00AM UTC.
- //
- // If this value isn't provided on job update, it depends on the field masks
- // set by [UpdateJobRequest.update_mask][google.cloud.talent.v4.UpdateJobRequest.update_mask]. If the field masks include
- // [job_end_time][google.cloud.talent.v4.Job.job_end_time], or the masks are empty meaning that every field is
- // updated, the job posting expires after 30 days from the job's last
- // update time. Otherwise the expiration date isn't updated.
- google.protobuf.Timestamp posting_expire_time = 25;
-
- // Output only. The timestamp when this job posting was created.
- google.protobuf.Timestamp posting_create_time = 26 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. The timestamp when this job posting was last updated.
- google.protobuf.Timestamp posting_update_time = 27 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Display name of the company listing the job.
- string company_display_name = 28 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Derived details about the job posting.
- DerivedInfo derived_info = 29 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Options for job processing.
- ProcessingOptions processing_options = 30;
-}
diff --git a/google/cloud/talent_v4/proto/job_service.proto b/google/cloud/talent_v4/proto/job_service.proto
deleted file mode 100644
index 37642927..00000000
--- a/google/cloud/talent_v4/proto/job_service.proto
+++ /dev/null
@@ -1,865 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4/common.proto";
-import "google/cloud/talent/v4/filters.proto";
-import "google/cloud/talent/v4/histogram.proto";
-import "google/cloud/talent/v4/job.proto";
-import "google/longrunning/operations.proto";
-import "google/protobuf/any.proto";
-import "google/protobuf/duration.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-import "google/rpc/status.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "JobServiceProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A service handles job management, including job CRUD, enumeration and search.
-service JobService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Creates a new job.
- //
- // Typically, the job becomes searchable within 10 seconds, but it may take
- // up to 5 minutes.
- rpc CreateJob(CreateJobRequest) returns (Job) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/jobs"
- body: "job"
- };
- option (google.api.method_signature) = "parent,job";
- }
-
- // Begins executing a batch create jobs operation.
- rpc BatchCreateJobs(BatchCreateJobsRequest) returns (google.longrunning.Operation) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/jobs:batchCreate"
- body: "*"
- };
- option (google.api.method_signature) = "parent,jobs";
- option (google.longrunning.operation_info) = {
- response_type: "BatchCreateJobsResponse"
- metadata_type: "BatchOperationMetadata"
- };
- }
-
- // Retrieves the specified job, whose status is OPEN or recently EXPIRED
- // within the last 90 days.
- rpc GetJob(GetJobRequest) returns (Job) {
- option (google.api.http) = {
- get: "/v4/{name=projects/*/tenants/*/jobs/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates specified job.
- //
- // Typically, updated contents become visible in search results within 10
- // seconds, but it may take up to 5 minutes.
- rpc UpdateJob(UpdateJobRequest) returns (Job) {
- option (google.api.http) = {
- patch: "/v4/{job.name=projects/*/tenants/*/jobs/*}"
- body: "job"
- };
- option (google.api.method_signature) = "job,update_mask";
- }
-
- // Begins executing a batch update jobs operation.
- rpc BatchUpdateJobs(BatchUpdateJobsRequest) returns (google.longrunning.Operation) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/jobs:batchUpdate"
- body: "*"
- };
- option (google.api.method_signature) = "parent,jobs";
- option (google.longrunning.operation_info) = {
- response_type: "BatchUpdateJobsResponse"
- metadata_type: "BatchOperationMetadata"
- };
- }
-
- // Deletes the specified job.
- //
- // Typically, the job becomes unsearchable within 10 seconds, but it may take
- // up to 5 minutes.
- rpc DeleteJob(DeleteJobRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4/{name=projects/*/tenants/*/jobs/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Begins executing a batch delete jobs operation.
- rpc BatchDeleteJobs(BatchDeleteJobsRequest) returns (google.longrunning.Operation) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/jobs:batchDelete"
- body: "*"
- };
- option (google.api.method_signature) = "parent,names";
- option (google.longrunning.operation_info) = {
- response_type: "BatchDeleteJobsResponse"
- metadata_type: "BatchOperationMetadata"
- };
- }
-
- // Lists jobs by filter.
- rpc ListJobs(ListJobsRequest) returns (ListJobsResponse) {
- option (google.api.http) = {
- get: "/v4/{parent=projects/*/tenants/*}/jobs"
- };
- option (google.api.method_signature) = "parent,filter";
- }
-
- // Searches for jobs using the provided [SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
- //
- // This call constrains the [visibility][google.cloud.talent.v4.Job.visibility] of jobs
- // present in the database, and only returns jobs that the caller has
- // permission to search against.
- rpc SearchJobs(SearchJobsRequest) returns (SearchJobsResponse) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/jobs:search"
- body: "*"
- };
- }
-
- // Searches for jobs using the provided [SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
- //
- // This API call is intended for the use case of targeting passive job
- // seekers (for example, job seekers who have signed up to receive email
- // alerts about potential job opportunities), it has different algorithmic
- // adjustments that are designed to specifically target passive job seekers.
- //
- // This call constrains the [visibility][google.cloud.talent.v4.Job.visibility] of jobs
- // present in the database, and only returns jobs the caller has
- // permission to search against.
- rpc SearchJobsForAlert(SearchJobsRequest) returns (SearchJobsResponse) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*/tenants/*}/jobs:searchForAlert"
- body: "*"
- };
- }
-}
-
-// Create job request.
-message CreateJobRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The Job to be created.
- Job job = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Get job request.
-message GetJobRequest {
- // Required. The resource name of the job to retrieve.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}". For
- // example, "projects/foo/tenants/bar/jobs/baz".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Job"
- }
- ];
-}
-
-// Update job request.
-message UpdateJobRequest {
- // Required. The Job to be updated.
- Job job = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // If [update_mask][google.cloud.talent.v4.UpdateJobRequest.update_mask] is provided, only the specified fields in
- // [job][google.cloud.talent.v4.UpdateJobRequest.job] are updated. Otherwise all the fields are updated.
- //
- // A field mask to restrict the fields that are updated. Only
- // top level fields of [Job][google.cloud.talent.v4.Job] are supported.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Delete job request.
-message DeleteJobRequest {
- // Required. The resource name of the job to be deleted.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}". For
- // example, "projects/foo/tenants/bar/jobs/baz".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Job"
- }
- ];
-}
-
-// List jobs request.
-message ListJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The filter string specifies the jobs to be enumerated.
- //
- // Supported operator: =, AND
- //
- // The fields eligible for filtering are:
- //
- // * `companyName` (Required)
- // * `requisitionId`
- // * `status` Available values: OPEN, EXPIRED, ALL. Defaults to
- // OPEN if no value is specified.
- //
- // Sample Query:
- //
- // * companyName = "projects/foo/tenants/bar/companies/baz"
- // * companyName = "projects/foo/tenants/bar/companies/baz" AND
- // requisitionId = "req-1"
- // * companyName = "projects/foo/tenants/bar/companies/baz" AND
- // status = "EXPIRED"
- string filter = 2 [(google.api.field_behavior) = REQUIRED];
-
- // The starting point of a query result.
- string page_token = 3;
-
- // The maximum number of jobs to be returned per page of results.
- //
- // If [job_view][google.cloud.talent.v4.ListJobsRequest.job_view] is set to [JobView.JOB_VIEW_ID_ONLY][google.cloud.talent.v4.JobView.JOB_VIEW_ID_ONLY], the maximum allowed
- // page size is 1000. Otherwise, the maximum allowed page size is 100.
- //
- // Default is 100 if empty or a number < 1 is specified.
- int32 page_size = 4;
-
- // The desired job attributes returned for jobs in the
- // search response. Defaults to [JobView.JOB_VIEW_FULL][google.cloud.talent.v4.JobView.JOB_VIEW_FULL] if no value is
- // specified.
- JobView job_view = 5;
-}
-
-// An enum that specifies the job attributes that are returned in the
-// [MatchingJob.job][google.cloud.talent.v4.SearchJobsResponse.MatchingJob.job] or
-// [ListJobsResponse.jobs][google.cloud.talent.v4.ListJobsResponse.jobs] fields.
-enum JobView {
- // Default value.
- JOB_VIEW_UNSPECIFIED = 0;
-
- // A ID only view of job, with following attributes:
- // [Job.name][google.cloud.talent.v4.Job.name], [Job.requisition_id][google.cloud.talent.v4.Job.requisition_id], [Job.language_code][google.cloud.talent.v4.Job.language_code].
- JOB_VIEW_ID_ONLY = 1;
-
- // A minimal view of the job, with the following attributes:
- // [Job.name][google.cloud.talent.v4.Job.name], [Job.requisition_id][google.cloud.talent.v4.Job.requisition_id], [Job.title][google.cloud.talent.v4.Job.title],
- // [Job.company][google.cloud.talent.v4.Job.company], [Job.DerivedInfo.locations][google.cloud.talent.v4.Job.DerivedInfo.locations], [Job.language_code][google.cloud.talent.v4.Job.language_code].
- JOB_VIEW_MINIMAL = 2;
-
- // A small view of the job, with the following attributes in the search
- // results: [Job.name][google.cloud.talent.v4.Job.name], [Job.requisition_id][google.cloud.talent.v4.Job.requisition_id], [Job.title][google.cloud.talent.v4.Job.title],
- // [Job.company][google.cloud.talent.v4.Job.company], [Job.DerivedInfo.locations][google.cloud.talent.v4.Job.DerivedInfo.locations], [Job.visibility][google.cloud.talent.v4.Job.visibility],
- // [Job.language_code][google.cloud.talent.v4.Job.language_code], [Job.description][google.cloud.talent.v4.Job.description].
- JOB_VIEW_SMALL = 3;
-
- // All available attributes are included in the search results.
- JOB_VIEW_FULL = 4;
-}
-
-// List jobs response.
-message ListJobsResponse {
- // The Jobs for a given company.
- //
- // The maximum number of items returned is based on the limit field
- // provided in the request.
- repeated Job jobs = 1;
-
- // A token to retrieve the next page of results.
- string next_page_token = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-}
-
-// The Request body of the `SearchJobs` call.
-message SearchJobsRequest {
- // Custom ranking information for [SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
- message CustomRankingInfo {
- // The importance level for [CustomRankingInfo.ranking_expression][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.ranking_expression].
- enum ImportanceLevel {
- // Default value if the importance level isn't specified.
- IMPORTANCE_LEVEL_UNSPECIFIED = 0;
-
- // The given ranking expression is of None importance, existing relevance
- // score (determined by API algorithm) dominates job's final ranking
- // position.
- NONE = 1;
-
- // The given ranking expression is of Low importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- LOW = 2;
-
- // The given ranking expression is of Mild importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- MILD = 3;
-
- // The given ranking expression is of Medium importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- MEDIUM = 4;
-
- // The given ranking expression is of High importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- HIGH = 5;
-
- // The given ranking expression is of Extreme importance, and dominates
- // job's final ranking position with existing relevance
- // score (determined by API algorithm) ignored.
- EXTREME = 6;
- }
-
- // Required. Controls over how important the score of
- // [CustomRankingInfo.ranking_expression][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.ranking_expression] gets applied to job's final
- // ranking position.
- //
- // An error is thrown if not specified.
- ImportanceLevel importance_level = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. Controls over how job documents get ranked on top of existing relevance
- // score (determined by API algorithm). A combination of the ranking
- // expression and relevance score is used to determine job's final ranking
- // position.
- //
- // The syntax for this expression is a subset of Google SQL syntax.
- //
- // Supported operators are: +, -, *, /, where the left and right side of
- // the operator is either a numeric [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes] key,
- // integer/double value or an expression that can be evaluated to a number.
- //
- // Parenthesis are supported to adjust calculation precedence. The
- // expression must be < 100 characters in length.
- //
- // The expression is considered invalid for a job if the expression
- // references custom attributes that are not populated on the job or if the
- // expression results in a divide by zero. If an expression is invalid for a
- // job, that job is demoted to the end of the results.
- //
- // Sample ranking expression
- // (year + 25) * 0.25 - (freshness / 0.5)
- string ranking_expression = 2 [(google.api.field_behavior) = REQUIRED];
- }
-
- // A string-represented enumeration of the job search mode. The service
- // operate differently for different modes of service.
- enum SearchMode {
- // The mode of the search method isn't specified. The default search
- // behavior is identical to JOB_SEARCH search behavior.
- SEARCH_MODE_UNSPECIFIED = 0;
-
- // The job search matches against all jobs, and featured jobs
- // (jobs with promotionValue > 0) are not specially handled.
- JOB_SEARCH = 1;
-
- // The job search matches only against featured jobs (jobs with a
- // promotionValue > 0). This method doesn't return any jobs having a
- // promotionValue <= 0. The search results order is determined by the
- // promotionValue (jobs with a higher promotionValue are returned higher up
- // in the search results), with relevance being used as a tiebreaker.
- FEATURED_JOB_SEARCH = 2;
- }
-
- // Controls whether highly similar jobs are returned next to each other in
- // the search results. Jobs are identified as highly similar based on
- // their titles, job categories, and locations. Highly similar results are
- // clustered so that only one representative job of the cluster is
- // displayed to the job seeker higher up in the results, with the other jobs
- // being displayed lower down in the results.
- enum DiversificationLevel {
- // The diversification level isn't specified.
- DIVERSIFICATION_LEVEL_UNSPECIFIED = 0;
-
- // Disables diversification. Jobs that would normally be pushed to the last
- // page would not have their positions altered. This may result in highly
- // similar jobs appearing in sequence in the search results.
- DISABLED = 1;
-
- // Default diversifying behavior. The result list is ordered so that
- // highly similar results are pushed to the end of the last page of search
- // results. If you are using pageToken to page through the result set,
- // latency might be lower but we can't guarantee that all results are
- // returned. If you are using page offset, latency might be higher but all
- // results are returned.
- SIMPLE = 2;
- }
-
- // Required. The resource name of the tenant to search within.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Mode of a search.
- //
- // Defaults to [SearchMode.JOB_SEARCH][google.cloud.talent.v4.SearchJobsRequest.SearchMode.JOB_SEARCH].
- SearchMode search_mode = 2;
-
- // Required. The meta information collected about the job searcher, used to improve the
- // search quality of the service. The identifiers (such as `user_id`) are
- // provided by users, and must be unique and consistent.
- RequestMetadata request_metadata = 3 [(google.api.field_behavior) = REQUIRED];
-
- // Query used to search against jobs, such as keyword, location filters, etc.
- JobQuery job_query = 4;
-
- // Controls whether to broaden the search when it produces sparse results.
- // Broadened queries append results to the end of the matching results
- // list.
- //
- // Defaults to false.
- bool enable_broadening = 5;
-
- // An expression specifies a histogram request against matching jobs.
- //
- // Expression syntax is an aggregation function call with histogram facets and
- // other options.
- //
- // Available aggregation function calls are:
- // * `count(string_histogram_facet)`: Count the number of matching entities,
- // for each distinct attribute value.
- // * `count(numeric_histogram_facet, list of buckets)`: Count the number of
- // matching entities within each bucket.
- //
- // Data types:
- //
- // * Histogram facet: facet names with format [a-zA-Z][a-zA-Z0-9_]+.
- // * String: string like "any string with backslash escape for quote(\")."
- // * Number: whole number and floating point number like 10, -1 and -0.01.
- // * List: list of elements with comma(,) separator surrounded by square
- // brackets, for example, [1, 2, 3] and ["one", "two", "three"].
- //
- // Built-in constants:
- //
- // * MIN (minimum number similar to java Double.MIN_VALUE)
- // * MAX (maximum number similar to java Double.MAX_VALUE)
- //
- // Built-in functions:
- //
- // * bucket(start, end[, label]): bucket built-in function creates a bucket
- // with range of [start, end). Note that the end is exclusive, for example,
- // bucket(1, MAX, "positive number") or bucket(1, 10).
- //
- // Job histogram facets:
- //
- // * company_display_name: histogram by [Job.company_display_name][google.cloud.talent.v4.Job.company_display_name].
- // * employment_type: histogram by [Job.employment_types][google.cloud.talent.v4.Job.employment_types], for example,
- // "FULL_TIME", "PART_TIME".
- // * company_size: histogram by [CompanySize][google.cloud.talent.v4.CompanySize], for example, "SMALL",
- // "MEDIUM", "BIG".
- // * publish_time_in_month: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time]
- // in months.
- // Must specify list of numeric buckets in spec.
- // * publish_time_in_year: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time]
- // in years.
- // Must specify list of numeric buckets in spec.
- // * degree_types: histogram by the [Job.degree_types][google.cloud.talent.v4.Job.degree_types], for example,
- // "Bachelors", "Masters".
- // * job_level: histogram by the [Job.job_level][google.cloud.talent.v4.Job.job_level], for example, "Entry
- // Level".
- // * country: histogram by the country code of jobs, for example, "US", "FR".
- // * admin1: histogram by the admin1 code of jobs, which is a global
- // placeholder referring to the state, province, or the particular term a
- // country uses to define the geographic structure below the country level,
- // for example, "CA", "IL".
- // * city: histogram by a combination of the "city name, admin1 code". For
- // example, "Mountain View, CA", "New York, NY".
- // * admin1_country: histogram by a combination of the "admin1 code, country",
- // for example, "CA, US", "IL, US".
- // * city_coordinate: histogram by the city center's GPS coordinates (latitude
- // and longitude), for example, 37.4038522,-122.0987765. Since the
- // coordinates of a city center can change, customers may need to refresh
- // them periodically.
- // * locale: histogram by the [Job.language_code][google.cloud.talent.v4.Job.language_code], for example, "en-US",
- // "fr-FR".
- // * language: histogram by the language subtag of the [Job.language_code][google.cloud.talent.v4.Job.language_code],
- // for example, "en", "fr".
- // * category: histogram by the [JobCategory][google.cloud.talent.v4.JobCategory], for example,
- // "COMPUTER_AND_IT", "HEALTHCARE".
- // * base_compensation_unit: histogram by the
- // [CompensationInfo.CompensationUnit][google.cloud.talent.v4.CompensationInfo.CompensationUnit] of base
- // salary, for example, "WEEKLY", "MONTHLY".
- // * base_compensation: histogram by the base salary. Must specify list of
- // numeric buckets to group results by.
- // * annualized_base_compensation: histogram by the base annualized salary.
- // Must specify list of numeric buckets to group results by.
- // * annualized_total_compensation: histogram by the total annualized salary.
- // Must specify list of numeric buckets to group results by.
- // * string_custom_attribute: histogram by string [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes].
- // Values can be accessed via square bracket notations like
- // string_custom_attribute["key1"].
- // * numeric_custom_attribute: histogram by numeric [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes].
- // Values can be accessed via square bracket notations like
- // numeric_custom_attribute["key1"]. Must specify list of numeric buckets to
- // group results by.
- //
- // Example expressions:
- //
- // * `count(admin1)`
- // * `count(base_compensation, [bucket(1000, 10000), bucket(10000, 100000),
- // bucket(100000, MAX)])`
- // * `count(string_custom_attribute["some-string-custom-attribute"])`
- // * `count(numeric_custom_attribute["some-numeric-custom-attribute"],
- // [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative"])`
- repeated HistogramQuery histogram_queries = 7;
-
- // The desired job attributes returned for jobs in the search response.
- // Defaults to [JobView.JOB_VIEW_SMALL][google.cloud.talent.v4.JobView.JOB_VIEW_SMALL] if no value is specified.
- JobView job_view = 8;
-
- // An integer that specifies the current offset (that is, starting result
- // location, amongst the jobs deemed by the API as relevant) in search
- // results. This field is only considered if [page_token][google.cloud.talent.v4.SearchJobsRequest.page_token] is unset.
- //
- // The maximum allowed value is 5000. Otherwise an error is thrown.
- //
- // For example, 0 means to return results starting from the first matching
- // job, and 10 means to return from the 11th job. This can be used for
- // pagination, (for example, pageSize = 10 and offset = 10 means to return
- // from the second page).
- int32 offset = 9;
-
- // A limit on the number of jobs returned in the search results.
- // Increasing this value above the default value of 10 can increase search
- // response time. The value can be between 1 and 100.
- int32 max_page_size = 10;
-
- // The token specifying the current offset within
- // search results. See [SearchJobsResponse.next_page_token][google.cloud.talent.v4.SearchJobsResponse.next_page_token] for
- // an explanation of how to obtain the next set of query results.
- string page_token = 11;
-
- // The criteria determining how search results are sorted. Default is
- // `"relevance desc"`.
- //
- // Supported options are:
- //
- // * `"relevance desc"`: By relevance descending, as determined by the API
- // algorithms. Relevance thresholding of query results is only available
- // with this ordering.
- // * `"posting_publish_time desc"`: By [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time]
- // descending.
- // * `"posting_update_time desc"`: By [Job.posting_update_time][google.cloud.talent.v4.Job.posting_update_time]
- // descending.
- // * `"title"`: By [Job.title][google.cloud.talent.v4.Job.title] ascending.
- // * `"title desc"`: By [Job.title][google.cloud.talent.v4.Job.title] descending.
- // * `"annualized_base_compensation"`: By job's
- // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_base_compensation_range] ascending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"annualized_base_compensation desc"`: By job's
- // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_base_compensation_range] descending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"annualized_total_compensation"`: By job's
- // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_total_compensation_range] ascending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"annualized_total_compensation desc"`: By job's
- // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_total_compensation_range] descending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"custom_ranking desc"`: By the relevance score adjusted to the
- // [SearchJobsRequest.CustomRankingInfo.ranking_expression][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.ranking_expression] with weight
- // factor assigned by
- // [SearchJobsRequest.CustomRankingInfo.importance_level][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.importance_level] in descending
- // order.
- // * Location sorting: Use the special syntax to order jobs by distance:
- // `"distance_from('Hawaii')"`: Order by distance from Hawaii.
- // `"distance_from(19.89, 155.5)"`: Order by distance from a coordinate.
- // `"distance_from('Hawaii'), distance_from('Puerto Rico')"`: Order by
- // multiple locations. See details below.
- // `"distance_from('Hawaii'), distance_from(19.89, 155.5)"`: Order by
- // multiple locations. See details below.
- // The string can have a maximum of 256 characters. When multiple distance
- // centers are provided, a job that is close to any of the distance centers
- // would have a high rank. When a job has multiple locations, the job
- // location closest to one of the distance centers will be used. Jobs that
- // don't have locations will be ranked at the bottom. Distance is calculated
- // with a precision of 11.3 meters (37.4 feet). Diversification strategy is
- // still applied unless explicitly disabled in
- // [diversification_level][google.cloud.talent.v4.SearchJobsRequest.diversification_level].
- string order_by = 12;
-
- // Controls whether highly similar jobs are returned next to each other in
- // the search results. Jobs are identified as highly similar based on
- // their titles, job categories, and locations. Highly similar results are
- // clustered so that only one representative job of the cluster is
- // displayed to the job seeker higher up in the results, with the other jobs
- // being displayed lower down in the results.
- //
- // Defaults to [DiversificationLevel.SIMPLE][google.cloud.talent.v4.SearchJobsRequest.DiversificationLevel.SIMPLE] if no value
- // is specified.
- DiversificationLevel diversification_level = 13;
-
- // Controls over how job documents get ranked on top of existing relevance
- // score (determined by API algorithm).
- CustomRankingInfo custom_ranking_info = 14;
-
- // Controls whether to disable exact keyword match on [Job.title][google.cloud.talent.v4.Job.title],
- // [Job.description][google.cloud.talent.v4.Job.description], [Job.company_display_name][google.cloud.talent.v4.Job.company_display_name], [Job.addresses][google.cloud.talent.v4.Job.addresses],
- // [Job.qualifications][google.cloud.talent.v4.Job.qualifications]. When disable keyword match is turned off, a
- // keyword match returns jobs that do not match given category filters when
- // there are matching keywords. For example, for the query "program manager,"
- // a result is returned even if the job posting has the title "software
- // developer," which doesn't fall into "program manager" ontology, but does
- // have "program manager" appearing in its description.
- //
- // For queries like "cloud" that don't contain title or
- // location specific ontology, jobs with "cloud" keyword matches are returned
- // regardless of this flag's value.
- //
- // Use [Company.keyword_searchable_job_custom_attributes][google.cloud.talent.v4.Company.keyword_searchable_job_custom_attributes] if
- // company-specific globally matched custom field/attribute string values are
- // needed. Enabling keyword match improves recall of subsequent search
- // requests.
- //
- // Defaults to false.
- bool disable_keyword_match = 16;
-}
-
-// Response for SearchJob method.
-message SearchJobsResponse {
- // Job entry with metadata inside [SearchJobsResponse][google.cloud.talent.v4.SearchJobsResponse].
- message MatchingJob {
- // Job resource that matches the specified [SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
- Job job = 1;
-
- // A summary of the job with core information that's displayed on the search
- // results listing page.
- string job_summary = 2;
-
- // Contains snippets of text from the [Job.title][google.cloud.talent.v4.Job.title] field most
- // closely matching a search query's keywords, if available. The matching
- // query keywords are enclosed in HTML bold tags.
- string job_title_snippet = 3;
-
- // Contains snippets of text from the [Job.description][google.cloud.talent.v4.Job.description] and similar
- // fields that most closely match a search query's keywords, if available.
- // All HTML tags in the original fields are stripped when returned in this
- // field, and matching query keywords are enclosed in HTML bold tags.
- string search_text_snippet = 4;
-
- // Commute information which is generated based on specified
- // [CommuteFilter][google.cloud.talent.v4.CommuteFilter].
- CommuteInfo commute_info = 5;
- }
-
- // Commute details related to this job.
- message CommuteInfo {
- // Location used as the destination in the commute calculation.
- Location job_location = 1;
-
- // The number of seconds required to travel to the job location from the
- // query location. A duration of 0 seconds indicates that the job isn't
- // reachable within the requested duration, but was returned as part of an
- // expanded query.
- google.protobuf.Duration travel_duration = 2;
- }
-
- // The Job entities that match the specified [SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
- repeated MatchingJob matching_jobs = 1;
-
- // The histogram results that match with specified
- // [SearchJobsRequest.histogram_queries][google.cloud.talent.v4.SearchJobsRequest.histogram_queries].
- repeated HistogramQueryResult histogram_query_results = 2;
-
- // The token that specifies the starting position of the next page of results.
- // This field is empty if there are no more results.
- string next_page_token = 3;
-
- // The location filters that the service applied to the specified query. If
- // any filters are lat-lng based, the [Location.location_type][google.cloud.talent.v4.Location.location_type] is
- // [Location.LocationType.LOCATION_TYPE_UNSPECIFIED][google.cloud.talent.v4.Location.LocationType.LOCATION_TYPE_UNSPECIFIED].
- repeated Location location_filters = 4;
-
- // Number of jobs that match the specified query.
- //
- // Note: This size is precise only if the total is less than 100,000.
- int32 total_size = 6;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 7;
-
- // If query broadening is enabled, we may append additional results from the
- // broadened query. This number indicates how many of the jobs returned in the
- // jobs field are from the broadened query. These results are always at the
- // end of the jobs list. In particular, a value of 0, or if the field isn't
- // set, all the jobs in the jobs list are from the original
- // (without broadening) query. If this field is non-zero, subsequent requests
- // with offset after this result set should contain all broadened results.
- int32 broadened_query_jobs_count = 8;
-
- // The spell checking result, and correction.
- SpellingCorrection spell_correction = 9;
-}
-
-// Request to create a batch of jobs.
-message BatchCreateJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The jobs to be created.
- // A maximum of 200 jobs can be created in a batch.
- repeated Job jobs = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Request to update a batch of jobs.
-message BatchUpdateJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The jobs to be updated.
- // A maximum of 200 jobs can be updated in a batch.
- repeated Job jobs = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience. Be aware that it will
- // also increase latency when checking the status of a batch operation.
- //
- // If [update_mask][google.cloud.talent.v4.BatchUpdateJobsRequest.update_mask] is provided, only the specified fields in
- // [Job][google.cloud.talent.v4.Job] are updated. Otherwise all the fields are updated.
- //
- // A field mask to restrict the fields that are updated. Only
- // top level fields of [Job][google.cloud.talent.v4.Job] are supported.
- //
- // If [update_mask][google.cloud.talent.v4.BatchUpdateJobsRequest.update_mask] is provided, The [Job][google.cloud.talent.v4.Job] inside
- // [JobResult][JobOperationResult.JobResult]
- // will only contains fields that is updated, plus the Id of the Job.
- // Otherwise, [Job][google.cloud.talent.v4.Job] will include all fields, which can yield a very
- // large response.
- google.protobuf.FieldMask update_mask = 3;
-}
-
-// Request to delete a batch of jobs.
-message BatchDeleteJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- //
- // The parent of all of the jobs specified in `names` must match this field.
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-
- // The names of the jobs to delete.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}".
- // For example, "projects/foo/tenants/bar/jobs/baz".
- //
- // A maximum of 200 jobs can be deleted in a batch.
- repeated string names = 2 [(google.api.resource_reference) = {
- type: "jobs.googleapis.com/Job"
- }];
-}
-
-// Mutation result of a job from a batch operation.
-message JobResult {
- // Here [Job][google.cloud.talent.v4.Job] only contains basic information including [name][google.cloud.talent.v4.Job.name],
- // [company][google.cloud.talent.v4.Job.company], [language_code][google.cloud.talent.v4.Job.language_code]
- // and [requisition_id][google.cloud.talent.v4.Job.requisition_id], use getJob method to retrieve
- // detailed information of the created/updated job.
- Job job = 1;
-
- // The status of the job processed. This field is populated if the
- // processing of the [job][google.cloud.talent.v4.JobResult.job] fails.
- google.rpc.Status status = 2;
-}
-
-// The result of [JobService.BatchCreateJobs][google.cloud.talent.v4.JobService.BatchCreateJobs]. It's used to
-// replace [google.longrunning.Operation.response][google.longrunning.Operation.response] in case of success.
-message BatchCreateJobsResponse {
- // List of job mutation results from a batch create operation. It can change
- // until operation status is FINISHED, FAILED or CANCELLED.
- repeated JobResult job_results = 1;
-}
-
-// The result of [JobService.BatchUpdateJobs][google.cloud.talent.v4.JobService.BatchUpdateJobs]. It's used to
-// replace [google.longrunning.Operation.response][google.longrunning.Operation.response] in case of success.
-message BatchUpdateJobsResponse {
- // List of job mutation results from a batch update operation. It can change
- // until operation status is FINISHED, FAILED or CANCELLED.
- repeated JobResult job_results = 1;
-}
-
-// The result of [JobService.BatchDeleteJobs][google.cloud.talent.v4.JobService.BatchDeleteJobs]. It's used to
-// replace [google.longrunning.Operation.response][google.longrunning.Operation.response] in case of success.
-message BatchDeleteJobsResponse {
- // List of job mutation results from a batch delete operation. It can change
- // until operation status is FINISHED, FAILED or CANCELLED.
- repeated JobResult job_results = 1;
-}
diff --git a/google/cloud/talent_v4/proto/tenant.proto b/google/cloud/talent_v4/proto/tenant.proto
deleted file mode 100644
index bdfa832d..00000000
--- a/google/cloud/talent_v4/proto/tenant.proto
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "TenantProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A Tenant resource represents a tenant in the service. A tenant is a group or
-// entity that shares common access with specific privileges for resources like
-// jobs. Customer may create multiple tenants to provide data isolation for
-// different groups.
-message Tenant {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Tenant"
- pattern: "projects/{project}/tenants/{tenant}"
- };
-
- // Required during tenant update.
- //
- // The resource name for a tenant. This is generated by the service when a
- // tenant is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string name = 1;
-
- // Required. Client side tenant identifier, used to uniquely identify the tenant.
- //
- // The maximum number of allowed characters is 255.
- string external_id = 2 [(google.api.field_behavior) = REQUIRED];
-}
diff --git a/google/cloud/talent_v4/proto/tenant_service.proto b/google/cloud/talent_v4/proto/tenant_service.proto
deleted file mode 100644
index a82d094f..00000000
--- a/google/cloud/talent_v4/proto/tenant_service.proto
+++ /dev/null
@@ -1,176 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4/common.proto";
-import "google/cloud/talent/v4/tenant.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4;talent";
-option java_multiple_files = true;
-option java_outer_classname = "TenantServiceProto";
-option java_package = "com.google.cloud.talent.v4";
-option objc_class_prefix = "CTS";
-
-// A service that handles tenant management, including CRUD and enumeration.
-service TenantService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Creates a new tenant entity.
- rpc CreateTenant(CreateTenantRequest) returns (Tenant) {
- option (google.api.http) = {
- post: "/v4/{parent=projects/*}/tenants"
- body: "tenant"
- };
- option (google.api.method_signature) = "parent,tenant";
- }
-
- // Retrieves specified tenant.
- rpc GetTenant(GetTenantRequest) returns (Tenant) {
- option (google.api.http) = {
- get: "/v4/{name=projects/*/tenants/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates specified tenant.
- rpc UpdateTenant(UpdateTenantRequest) returns (Tenant) {
- option (google.api.http) = {
- patch: "/v4/{tenant.name=projects/*/tenants/*}"
- body: "tenant"
- };
- option (google.api.method_signature) = "tenant,update_mask";
- }
-
- // Deletes specified tenant.
- rpc DeleteTenant(DeleteTenantRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4/{name=projects/*/tenants/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Lists all tenants associated with the project.
- rpc ListTenants(ListTenantsRequest) returns (ListTenantsResponse) {
- option (google.api.http) = {
- get: "/v4/{parent=projects/*}/tenants"
- };
- option (google.api.method_signature) = "parent";
- }
-}
-
-// The Request of the CreateTenant method.
-message CreateTenantRequest {
- // Required. Resource name of the project under which the tenant is created.
- //
- // The format is "projects/{project_id}", for example,
- // "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "cloudresourcemanager.googleapis.com/Project"
- }
- ];
-
- // Required. The tenant to be created.
- Tenant tenant = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Request for getting a tenant by name.
-message GetTenantRequest {
- // Required. The resource name of the tenant to be retrieved.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-}
-
-// Request for updating a specified tenant.
-message UpdateTenantRequest {
- // Required. The tenant resource to replace the current resource in the system.
- Tenant tenant = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // If [update_mask][google.cloud.talent.v4.UpdateTenantRequest.update_mask] is provided, only the specified fields in
- // [tenant][google.cloud.talent.v4.UpdateTenantRequest.tenant] are updated. Otherwise all the fields are updated.
- //
- // A field mask to specify the tenant fields to be updated. Only
- // top level fields of [Tenant][google.cloud.talent.v4.Tenant] are supported.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Request to delete a tenant.
-message DeleteTenantRequest {
- // Required. The resource name of the tenant to be deleted.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-}
-
-// List tenants for which the client has ACL visibility.
-message ListTenantsRequest {
- // Required. Resource name of the project under which the tenant is created.
- //
- // The format is "projects/{project_id}", for example,
- // "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "cloudresourcemanager.googleapis.com/Project"
- }
- ];
-
- // The starting indicator from which to return results.
- string page_token = 2;
-
- // The maximum number of tenants to be returned, at most 100.
- // Default is 100 if a non-positive number is provided.
- int32 page_size = 3;
-}
-
-// The List tenants response object.
-message ListTenantsResponse {
- // Tenants for the current client.
- repeated Tenant tenants = 1;
-
- // A token to retrieve the next page of results.
- string next_page_token = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-}
diff --git a/google/cloud/talent_v4/services/__init__.py b/google/cloud/talent_v4/services/__init__.py
index 42ffdf2b..4de65971 100644
--- a/google/cloud/talent_v4/services/__init__.py
+++ b/google/cloud/talent_v4/services/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/google/cloud/talent_v4/services/company_service/__init__.py b/google/cloud/talent_v4/services/company_service/__init__.py
index a7154172..6849b6f3 100644
--- a/google/cloud/talent_v4/services/company_service/__init__.py
+++ b/google/cloud/talent_v4/services/company_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import CompanyServiceClient
from .async_client import CompanyServiceAsyncClient
diff --git a/google/cloud/talent_v4/services/company_service/async_client.py b/google/cloud/talent_v4/services/company_service/async_client.py
index dc84e1fd..ef3ae6a6 100644
--- a/google/cloud/talent_v4/services/company_service/async_client.py
+++ b/google/cloud/talent_v4/services/company_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,10 +20,10 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.services.company_service import pagers
@@ -33,8 +31,7 @@
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company as gct_company
from google.cloud.talent_v4.types import company_service
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-
+from google.protobuf import field_mask_pb2 # type: ignore
from .transports.base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import CompanyServiceGrpcAsyncIOTransport
from .client import CompanyServiceClient
@@ -54,42 +51,67 @@ class CompanyServiceAsyncClient:
parse_company_path = staticmethod(CompanyServiceClient.parse_company_path)
tenant_path = staticmethod(CompanyServiceClient.tenant_path)
parse_tenant_path = staticmethod(CompanyServiceClient.parse_tenant_path)
-
common_billing_account_path = staticmethod(
CompanyServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
CompanyServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(CompanyServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(
CompanyServiceClient.parse_common_folder_path
)
-
common_organization_path = staticmethod(
CompanyServiceClient.common_organization_path
)
parse_common_organization_path = staticmethod(
CompanyServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(CompanyServiceClient.common_project_path)
parse_common_project_path = staticmethod(
CompanyServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(CompanyServiceClient.common_location_path)
parse_common_location_path = staticmethod(
CompanyServiceClient.parse_common_location_path
)
- from_service_account_file = CompanyServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompanyServiceAsyncClient: The constructed client.
+ """
+ return CompanyServiceClient.from_service_account_info.__func__(CompanyServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompanyServiceAsyncClient: The constructed client.
+ """
+ return CompanyServiceClient.from_service_account_file.__func__(CompanyServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> CompanyServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
CompanyServiceTransport: The transport used by the client instance.
@@ -103,12 +125,12 @@ def transport(self) -> CompanyServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, CompanyServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the company service client.
+ """Instantiates the company service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -140,7 +162,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = CompanyServiceClient(
credentials=credentials,
transport=transport,
@@ -161,7 +182,7 @@ async def create_company(
r"""Creates a new company entity.
Args:
- request (:class:`~.company_service.CreateCompanyRequest`):
+ request (:class:`google.cloud.talent_v4.types.CreateCompanyRequest`):
The request object. The Request of the CreateCompany
method.
parent (:class:`str`):
@@ -171,15 +192,15 @@ async def create_company(
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- company (:class:`~.gct_company.Company`):
+ company (:class:`google.cloud.talent_v4.types.Company`):
Required. The company to be created.
This corresponds to the ``company`` 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.
@@ -187,7 +208,7 @@ async def create_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -210,7 +231,6 @@ async def create_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if company is not None:
@@ -248,7 +268,7 @@ async def get_company(
r"""Retrieves specified company.
Args:
- request (:class:`~.company_service.GetCompanyRequest`):
+ request (:class:`google.cloud.talent_v4.types.GetCompanyRequest`):
The request object. Request for getting a company by
name.
name (:class:`str`):
@@ -259,10 +279,10 @@ async def get_company(
"projects/{project_id}/tenants/{tenant_id}/companies/{company_id}",
for example,
"projects/api-test-project/tenants/foo/companies/bar".
+
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.
@@ -270,7 +290,7 @@ async def get_company(
sent along with the request as metadata.
Returns:
- ~.company.Company:
+ google.cloud.talent_v4.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -293,7 +313,6 @@ async def get_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -306,8 +325,10 @@ async def get_company(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -330,7 +351,7 @@ async def update_company(
request: company_service.UpdateCompanyRequest = None,
*,
company: gct_company.Company = None,
- update_mask: field_mask.FieldMask = None,
+ update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
@@ -338,17 +359,18 @@ async def update_company(
r"""Updates specified company.
Args:
- request (:class:`~.company_service.UpdateCompanyRequest`):
+ request (:class:`google.cloud.talent_v4.types.UpdateCompanyRequest`):
The request object. Request for updating a specified
company.
- company (:class:`~.gct_company.Company`):
+ company (:class:`google.cloud.talent_v4.types.Company`):
Required. The company resource to
replace the current resource in the
system.
+
This corresponds to the ``company`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- update_mask (:class:`~.field_mask.FieldMask`):
+ update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
Strongly recommended for the best service experience.
If
@@ -360,10 +382,10 @@ async def update_company(
A field mask to specify the company fields to be
updated. Only top level fields of
[Company][google.cloud.talent.v4.Company] are supported.
+
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.
@@ -371,7 +393,7 @@ async def update_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -394,7 +416,6 @@ async def update_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if company is not None:
request.company = company
if update_mask is not None:
@@ -436,7 +457,7 @@ async def delete_company(
it.
Args:
- request (:class:`~.company_service.DeleteCompanyRequest`):
+ request (:class:`google.cloud.talent_v4.types.DeleteCompanyRequest`):
The request object. Request to delete a company.
name (:class:`str`):
Required. The resource name of the company to be
@@ -445,10 +466,10 @@ async def delete_company(
The format is
"projects/{project_id}/tenants/{tenant_id}/companies/{company_id}",
for example, "projects/foo/tenants/bar/companies/baz".
+
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.
@@ -469,7 +490,6 @@ async def delete_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -482,8 +502,10 @@ async def delete_company(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -512,7 +534,7 @@ async def list_companies(
r"""Lists all companies associated with the project.
Args:
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (:class:`google.cloud.talent_v4.types.ListCompaniesRequest`):
The request object. List companies for which the client
has ACL visibility.
parent (:class:`str`):
@@ -522,10 +544,10 @@ async def list_companies(
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -533,7 +555,7 @@ async def list_companies(
sent along with the request as metadata.
Returns:
- ~.pagers.ListCompaniesAsyncPager:
+ google.cloud.talent_v4.services.company_service.pagers.ListCompaniesAsyncPager:
The List companies response object.
Iterating over this object will yield
results and resolve additional pages
@@ -554,7 +576,6 @@ async def list_companies(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
@@ -567,8 +588,10 @@ async def list_companies(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
diff --git a/google/cloud/talent_v4/services/company_service/client.py b/google/cloud/talent_v4/services/company_service/client.py
index 7b32d9b6..c5a3956f 100644
--- a/google/cloud/talent_v4/services/company_service/client.py
+++ b/google/cloud/talent_v4/services/company_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -37,8 +35,7 @@
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company as gct_company
from google.cloud.talent_v4.types import company_service
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-
+from google.protobuf import field_mask_pb2 # type: ignore
from .transports.base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import CompanyServiceGrpcTransport
from .transports.grpc_asyncio import CompanyServiceGrpcAsyncIOTransport
@@ -59,7 +56,7 @@ class CompanyServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = CompanyServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[CompanyServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -84,7 +81,8 @@ class CompanyServiceClient(metaclass=CompanyServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -116,10 +114,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompanyServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -128,7 +143,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ CompanyServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -138,23 +153,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> CompanyServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- CompanyServiceTransport: The transport used by the client instance.
+ CompanyServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -163,20 +179,20 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def tenant_path(project: str, tenant: str,) -> str:
- """Return a fully-qualified tenant string."""
+ """Returns a fully-qualified tenant string."""
return "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@staticmethod
def parse_tenant_path(path: str) -> Dict[str, str]:
- """Parse a tenant path into its component segments."""
+ """Parses a tenant path into its component segments."""
m = re.match(r"^projects/(?P.+?)/tenants/(?P.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -189,7 +205,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -200,7 +216,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -211,7 +227,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -222,7 +238,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -236,12 +252,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, CompanyServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the company service client.
+ """Instantiates the company service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -249,10 +265,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.CompanyServiceTransport]): The
+ transport (Union[str, CompanyServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -288,21 +304,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -314,12 +327,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -334,8 +349,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -345,7 +360,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -363,25 +378,25 @@ def create_company(
r"""Creates a new company entity.
Args:
- request (:class:`~.company_service.CreateCompanyRequest`):
+ request (google.cloud.talent_v4.types.CreateCompanyRequest):
The request object. The Request of the CreateCompany
method.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the tenant under which the
company is created.
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- company (:class:`~.gct_company.Company`):
+ company (google.cloud.talent_v4.types.Company):
Required. The company to be created.
This corresponds to the ``company`` 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.
@@ -389,7 +404,7 @@ def create_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -414,10 +429,8 @@ def create_company(
# there are no flattened fields.
if not isinstance(request, company_service.CreateCompanyRequest):
request = company_service.CreateCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if company is not None:
@@ -451,10 +464,10 @@ def get_company(
r"""Retrieves specified company.
Args:
- request (:class:`~.company_service.GetCompanyRequest`):
+ request (google.cloud.talent_v4.types.GetCompanyRequest):
The request object. Request for getting a company by
name.
- name (:class:`str`):
+ name (str):
Required. The resource name of the company to be
retrieved.
@@ -462,10 +475,10 @@ def get_company(
"projects/{project_id}/tenants/{tenant_id}/companies/{company_id}",
for example,
"projects/api-test-project/tenants/foo/companies/bar".
+
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.
@@ -473,7 +486,7 @@ def get_company(
sent along with the request as metadata.
Returns:
- ~.company.Company:
+ google.cloud.talent_v4.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -498,10 +511,8 @@ def get_company(
# there are no flattened fields.
if not isinstance(request, company_service.GetCompanyRequest):
request = company_service.GetCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -526,7 +537,7 @@ def update_company(
request: company_service.UpdateCompanyRequest = None,
*,
company: gct_company.Company = None,
- update_mask: field_mask.FieldMask = None,
+ update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
@@ -534,17 +545,18 @@ def update_company(
r"""Updates specified company.
Args:
- request (:class:`~.company_service.UpdateCompanyRequest`):
+ request (google.cloud.talent_v4.types.UpdateCompanyRequest):
The request object. Request for updating a specified
company.
- company (:class:`~.gct_company.Company`):
+ company (google.cloud.talent_v4.types.Company):
Required. The company resource to
replace the current resource in the
system.
+
This corresponds to the ``company`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- update_mask (:class:`~.field_mask.FieldMask`):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -556,10 +568,10 @@ def update_company(
A field mask to specify the company fields to be
updated. Only top level fields of
[Company][google.cloud.talent.v4.Company] are supported.
+
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.
@@ -567,7 +579,7 @@ def update_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -592,10 +604,8 @@ def update_company(
# there are no flattened fields.
if not isinstance(request, company_service.UpdateCompanyRequest):
request = company_service.UpdateCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if company is not None:
request.company = company
if update_mask is not None:
@@ -633,19 +643,19 @@ def delete_company(
it.
Args:
- request (:class:`~.company_service.DeleteCompanyRequest`):
+ request (google.cloud.talent_v4.types.DeleteCompanyRequest):
The request object. Request to delete a company.
- name (:class:`str`):
+ name (str):
Required. The resource name of the company to be
deleted.
The format is
"projects/{project_id}/tenants/{tenant_id}/companies/{company_id}",
for example, "projects/foo/tenants/bar/companies/baz".
+
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.
@@ -668,10 +678,8 @@ def delete_company(
# there are no flattened fields.
if not isinstance(request, company_service.DeleteCompanyRequest):
request = company_service.DeleteCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -702,20 +710,20 @@ def list_companies(
r"""Lists all companies associated with the project.
Args:
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (google.cloud.talent_v4.types.ListCompaniesRequest):
The request object. List companies for which the client
has ACL visibility.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the tenant under which the
company is created.
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -723,7 +731,7 @@ def list_companies(
sent along with the request as metadata.
Returns:
- ~.pagers.ListCompaniesPager:
+ google.cloud.talent_v4.services.company_service.pagers.ListCompaniesPager:
The List companies response object.
Iterating over this object will yield
results and resolve additional pages
@@ -746,10 +754,8 @@ def list_companies(
# there are no flattened fields.
if not isinstance(request, company_service.ListCompaniesRequest):
request = company_service.ListCompaniesRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
diff --git a/google/cloud/talent_v4/services/company_service/pagers.py b/google/cloud/talent_v4/services/company_service/pagers.py
index 992c4b53..e354338d 100644
--- a/google/cloud/talent_v4/services/company_service/pagers.py
+++ b/google/cloud/talent_v4/services/company_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company_service
@@ -25,7 +32,7 @@ class ListCompaniesPager:
"""A pager for iterating through ``list_companies`` requests.
This class thinly wraps an initial
- :class:`~.company_service.ListCompaniesResponse` object, and
+ :class:`google.cloud.talent_v4.types.ListCompaniesResponse` object, and
provides an ``__iter__`` method to iterate through its
``companies`` field.
@@ -34,7 +41,7 @@ class ListCompaniesPager:
through the ``companies`` field on the
corresponding responses.
- All the usual :class:`~.company_service.ListCompaniesResponse`
+ All the usual :class:`google.cloud.talent_v4.types.ListCompaniesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -52,9 +59,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (google.cloud.talent_v4.types.ListCompaniesRequest):
The initial request object.
- response (:class:`~.company_service.ListCompaniesResponse`):
+ response (google.cloud.talent_v4.types.ListCompaniesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -87,7 +94,7 @@ class ListCompaniesAsyncPager:
"""A pager for iterating through ``list_companies`` requests.
This class thinly wraps an initial
- :class:`~.company_service.ListCompaniesResponse` object, and
+ :class:`google.cloud.talent_v4.types.ListCompaniesResponse` object, and
provides an ``__aiter__`` method to iterate through its
``companies`` field.
@@ -96,7 +103,7 @@ class ListCompaniesAsyncPager:
through the ``companies`` field on the
corresponding responses.
- All the usual :class:`~.company_service.ListCompaniesResponse`
+ All the usual :class:`google.cloud.talent_v4.types.ListCompaniesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -109,14 +116,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (google.cloud.talent_v4.types.ListCompaniesRequest):
The initial request object.
- response (:class:`~.company_service.ListCompaniesResponse`):
+ response (google.cloud.talent_v4.types.ListCompaniesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4/services/company_service/transports/__init__.py b/google/cloud/talent_v4/services/company_service/transports/__init__.py
index 51e34763..e8b8e830 100644
--- a/google/cloud/talent_v4/services/company_service/transports/__init__.py
+++ b/google/cloud/talent_v4/services/company_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4/services/company_service/transports/base.py b/google/cloud/talent_v4/services/company_service/transports/base.py
index 587ed0c6..a4680262 100644
--- a/google/cloud/talent_v4/services/company_service/transports/base.py
+++ b/google/cloud/talent_v4/services/company_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company as gct_company
from google.cloud.talent_v4.types import company_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -38,6 +38,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class CompanyServiceTransport(abc.ABC):
"""Abstract transport class for CompanyService."""
@@ -47,21 +56,25 @@ class CompanyServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -70,42 +83,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -120,8 +168,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -136,8 +186,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -149,8 +201,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -160,47 +214,47 @@ def _prep_wrapped_messages(self, client_info):
@property
def create_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.CreateCompanyRequest],
- typing.Union[gct_company.Company, typing.Awaitable[gct_company.Company]],
+ Union[gct_company.Company, Awaitable[gct_company.Company]],
]:
raise NotImplementedError()
@property
def get_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.GetCompanyRequest],
- typing.Union[company.Company, typing.Awaitable[company.Company]],
+ Union[company.Company, Awaitable[company.Company]],
]:
raise NotImplementedError()
@property
def update_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.UpdateCompanyRequest],
- typing.Union[gct_company.Company, typing.Awaitable[gct_company.Company]],
+ Union[gct_company.Company, Awaitable[gct_company.Company]],
]:
raise NotImplementedError()
@property
def delete_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.DeleteCompanyRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_companies(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.ListCompaniesRequest],
- typing.Union[
+ Union[
company_service.ListCompaniesResponse,
- typing.Awaitable[company_service.ListCompaniesResponse],
+ Awaitable[company_service.ListCompaniesResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4/services/company_service/transports/grpc.py b/google/cloud/talent_v4/services/company_service/transports/grpc.py
index 09068973..aefcd800 100644
--- a/google/cloud/talent_v4/services/company_service/transports/grpc.py
+++ b/google/cloud/talent_v4/services/company_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -29,8 +27,7 @@
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company as gct_company
from google.cloud.talent_v4.types import company_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
@@ -54,20 +51,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -91,6 +91,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -98,6 +102,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -105,72 +111,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -178,23 +173,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -202,7 +188,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -225,13 +211,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -322,7 +310,7 @@ def update_company(
@property
def delete_company(
self,
- ) -> Callable[[company_service.DeleteCompanyRequest], empty.Empty]:
+ ) -> Callable[[company_service.DeleteCompanyRequest], empty_pb2.Empty]:
r"""Return a callable for the delete company method over gRPC.
Deletes specified company.
@@ -343,7 +331,7 @@ def delete_company(
self._stubs["delete_company"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.CompanyService/DeleteCompany",
request_serializer=company_service.DeleteCompanyRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_company"]
diff --git a/google/cloud/talent_v4/services/company_service/transports/grpc_asyncio.py b/google/cloud/talent_v4/services/company_service/transports/grpc_asyncio.py
index fbf3fa4a..24aa0045 100644
--- a/google/cloud/talent_v4/services/company_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4/services/company_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -30,8 +28,7 @@
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company as gct_company
from google.cloud.talent_v4.types import company_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import CompanyServiceGrpcTransport
@@ -57,7 +54,7 @@ class CompanyServiceGrpcAsyncIOTransport(CompanyServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -65,7 +62,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -84,13 +81,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -98,20 +97,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -136,13 +138,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -150,72 +158,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -223,17 +219,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -330,7 +317,7 @@ def update_company(
@property
def delete_company(
self,
- ) -> Callable[[company_service.DeleteCompanyRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[company_service.DeleteCompanyRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the delete company method over gRPC.
Deletes specified company.
@@ -351,7 +338,7 @@ def delete_company(
self._stubs["delete_company"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.CompanyService/DeleteCompany",
request_serializer=company_service.DeleteCompanyRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_company"]
diff --git a/google/cloud/talent_v4/services/completion/__init__.py b/google/cloud/talent_v4/services/completion/__init__.py
index 0c274210..fb544ebc 100644
--- a/google/cloud/talent_v4/services/completion/__init__.py
+++ b/google/cloud/talent_v4/services/completion/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import CompletionClient
from .async_client import CompletionAsyncClient
diff --git a/google/cloud/talent_v4/services/completion/async_client.py b/google/cloud/talent_v4/services/completion/async_client.py
index 2c91e861..f7cc58c2 100644
--- a/google/cloud/talent_v4/services/completion/async_client.py
+++ b/google/cloud/talent_v4/services/completion/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,15 +20,14 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import completion_service
-
from .transports.base import CompletionTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import CompletionGrpcAsyncIOTransport
from .client import CompletionClient
@@ -48,36 +45,61 @@ class CompletionAsyncClient:
parse_company_path = staticmethod(CompletionClient.parse_company_path)
tenant_path = staticmethod(CompletionClient.tenant_path)
parse_tenant_path = staticmethod(CompletionClient.parse_tenant_path)
-
common_billing_account_path = staticmethod(
CompletionClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
CompletionClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(CompletionClient.common_folder_path)
parse_common_folder_path = staticmethod(CompletionClient.parse_common_folder_path)
-
common_organization_path = staticmethod(CompletionClient.common_organization_path)
parse_common_organization_path = staticmethod(
CompletionClient.parse_common_organization_path
)
-
common_project_path = staticmethod(CompletionClient.common_project_path)
parse_common_project_path = staticmethod(CompletionClient.parse_common_project_path)
-
common_location_path = staticmethod(CompletionClient.common_location_path)
parse_common_location_path = staticmethod(
CompletionClient.parse_common_location_path
)
- from_service_account_file = CompletionClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompletionAsyncClient: The constructed client.
+ """
+ return CompletionClient.from_service_account_info.__func__(CompletionAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompletionAsyncClient: The constructed client.
+ """
+ return CompletionClient.from_service_account_file.__func__(CompletionAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> CompletionTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
CompletionTransport: The transport used by the client instance.
@@ -91,12 +113,12 @@ def transport(self) -> CompletionTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, CompletionTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the completion client.
+ """Instantiates the completion client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -128,7 +150,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = CompletionClient(
credentials=credentials,
transport=transport,
@@ -149,9 +170,8 @@ async def complete_query(
complete search box.
Args:
- request (:class:`~.completion_service.CompleteQueryRequest`):
+ request (:class:`google.cloud.talent_v4.types.CompleteQueryRequest`):
The request object. Auto-complete parameters.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -159,11 +179,10 @@ async def complete_query(
sent along with the request as metadata.
Returns:
- ~.completion_service.CompleteQueryResponse:
+ google.cloud.talent_v4.types.CompleteQueryResponse:
Response of auto-complete query.
"""
# Create or coerce a protobuf request object.
-
request = completion_service.CompleteQueryRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
@@ -175,8 +194,10 @@ async def complete_query(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
diff --git a/google/cloud/talent_v4/services/completion/client.py b/google/cloud/talent_v4/services/completion/client.py
index 3d3b0589..f1533efb 100644
--- a/google/cloud/talent_v4/services/completion/client.py
+++ b/google/cloud/talent_v4/services/completion/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -34,7 +32,6 @@
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import completion_service
-
from .transports.base import CompletionTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import CompletionGrpcTransport
from .transports.grpc_asyncio import CompletionGrpcAsyncIOTransport
@@ -53,7 +50,7 @@ class CompletionClientMeta(type):
_transport_registry["grpc_asyncio"] = CompletionGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[CompletionTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -76,7 +73,8 @@ class CompletionClient(metaclass=CompletionClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -108,10 +106,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompletionClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -120,7 +135,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ CompletionClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -130,23 +145,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> CompletionTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- CompletionTransport: The transport used by the client instance.
+ CompletionTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -155,20 +171,20 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def tenant_path(project: str, tenant: str,) -> str:
- """Return a fully-qualified tenant string."""
+ """Returns a fully-qualified tenant string."""
return "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@staticmethod
def parse_tenant_path(path: str) -> Dict[str, str]:
- """Parse a tenant path into its component segments."""
+ """Parses a tenant path into its component segments."""
m = re.match(r"^projects/(?P.+?)/tenants/(?P.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -181,7 +197,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -192,7 +208,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -203,7 +219,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -214,7 +230,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -228,12 +244,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, CompletionTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the completion client.
+ """Instantiates the completion client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -241,10 +257,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.CompletionTransport]): The
+ transport (Union[str, CompletionTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -280,21 +296,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -306,12 +319,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -326,8 +341,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -337,7 +352,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -355,9 +370,8 @@ def complete_query(
complete search box.
Args:
- request (:class:`~.completion_service.CompleteQueryRequest`):
+ request (google.cloud.talent_v4.types.CompleteQueryRequest):
The request object. Auto-complete parameters.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -365,11 +379,10 @@ def complete_query(
sent along with the request as metadata.
Returns:
- ~.completion_service.CompleteQueryResponse:
+ google.cloud.talent_v4.types.CompleteQueryResponse:
Response of auto-complete query.
"""
# Create or coerce a protobuf request object.
-
# Minor optimization to avoid making a copy if the user passes
# in a completion_service.CompleteQueryRequest.
# There's no risk of modifying the input as we've already verified
diff --git a/google/cloud/talent_v4/services/completion/transports/__init__.py b/google/cloud/talent_v4/services/completion/transports/__init__.py
index df284f3e..01ea0e8d 100644
--- a/google/cloud/talent_v4/services/completion/transports/__init__.py
+++ b/google/cloud/talent_v4/services/completion/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4/services/completion/transports/base.py b/google/cloud/talent_v4/services/completion/transports/base.py
index efb1e327..95edf7a4 100644
--- a/google/cloud/talent_v4/services/completion/transports/base.py
+++ b/google/cloud/talent_v4/services/completion/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,20 +13,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.types import completion_service
-
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution("google-cloud-talent",).version,
@@ -35,6 +35,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class CompletionTransport(abc.ABC):
"""Abstract transport class for Completion."""
@@ -44,21 +53,25 @@ class CompletionTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -67,42 +80,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -114,8 +162,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -125,11 +175,11 @@ def _prep_wrapped_messages(self, client_info):
@property
def complete_query(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[completion_service.CompleteQueryRequest],
- typing.Union[
+ Union[
completion_service.CompleteQueryResponse,
- typing.Awaitable[completion_service.CompleteQueryResponse],
+ Awaitable[completion_service.CompleteQueryResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4/services/completion/transports/grpc.py b/google/cloud/talent_v4/services/completion/transports/grpc.py
index 08fe29d3..3b272950 100644
--- a/google/cloud/talent_v4/services/completion/transports/grpc.py
+++ b/google/cloud/talent_v4/services/completion/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,20 +13,18 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.cloud.talent_v4.types import completion_service
-
from .base import CompletionTransport, DEFAULT_CLIENT_INFO
@@ -50,20 +47,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -87,6 +87,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -94,6 +98,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -101,72 +107,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -174,23 +169,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -198,7 +184,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -221,13 +207,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
diff --git a/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py b/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py
index d5a0ef57..b4c6bc68 100644
--- a/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,21 +13,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
from google.cloud.talent_v4.types import completion_service
-
from .base import CompletionTransport, DEFAULT_CLIENT_INFO
from .grpc import CompletionGrpcTransport
@@ -53,7 +50,7 @@ class CompletionGrpcAsyncIOTransport(CompletionTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -61,7 +58,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -80,13 +77,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -94,20 +93,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -132,13 +134,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -146,72 +154,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -219,17 +215,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
diff --git a/google/cloud/talent_v4/services/event_service/__init__.py b/google/cloud/talent_v4/services/event_service/__init__.py
index f321845c..d58ce120 100644
--- a/google/cloud/talent_v4/services/event_service/__init__.py
+++ b/google/cloud/talent_v4/services/event_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import EventServiceClient
from .async_client import EventServiceAsyncClient
diff --git a/google/cloud/talent_v4/services/event_service/async_client.py b/google/cloud/talent_v4/services/event_service/async_client.py
index 8a6a6e41..314e6cbc 100644
--- a/google/cloud/talent_v4/services/event_service/async_client.py
+++ b/google/cloud/talent_v4/services/event_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,16 +20,15 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.types import event
from google.cloud.talent_v4.types import event_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import EventServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import EventServiceGrpcAsyncIOTransport
from .client import EventServiceClient
@@ -47,38 +44,63 @@ class EventServiceAsyncClient:
tenant_path = staticmethod(EventServiceClient.tenant_path)
parse_tenant_path = staticmethod(EventServiceClient.parse_tenant_path)
-
common_billing_account_path = staticmethod(
EventServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
EventServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(EventServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(EventServiceClient.parse_common_folder_path)
-
common_organization_path = staticmethod(EventServiceClient.common_organization_path)
parse_common_organization_path = staticmethod(
EventServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(EventServiceClient.common_project_path)
parse_common_project_path = staticmethod(
EventServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(EventServiceClient.common_location_path)
parse_common_location_path = staticmethod(
EventServiceClient.parse_common_location_path
)
- from_service_account_file = EventServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ EventServiceAsyncClient: The constructed client.
+ """
+ return EventServiceClient.from_service_account_info.__func__(EventServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ EventServiceAsyncClient: The constructed client.
+ """
+ return EventServiceClient.from_service_account_file.__func__(EventServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> EventServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
EventServiceTransport: The transport used by the client instance.
@@ -92,12 +114,12 @@ def transport(self) -> EventServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, EventServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the event service client.
+ """Instantiates the event service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -129,7 +151,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = EventServiceClient(
credentials=credentials,
transport=transport,
@@ -156,7 +177,7 @@ async def create_client_event(
about self service tools.
Args:
- request (:class:`~.event_service.CreateClientEventRequest`):
+ request (:class:`google.cloud.talent_v4.types.CreateClientEventRequest`):
The request object. The report event request.
parent (:class:`str`):
Required. Resource name of the tenant under which the
@@ -165,17 +186,18 @@ async def create_client_event(
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- client_event (:class:`~.event.ClientEvent`):
+ client_event (:class:`google.cloud.talent_v4.types.ClientEvent`):
Required. Events issued when end user
interacts with customer's application
that uses Cloud Talent Solution.
+
This corresponds to the ``client_event`` 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.
@@ -183,7 +205,7 @@ async def create_client_event(
sent along with the request as metadata.
Returns:
- ~.event.ClientEvent:
+ google.cloud.talent_v4.types.ClientEvent:
An event issued when an end user
interacts with the application that
implements Cloud Talent Solution.
@@ -210,7 +232,6 @@ async def create_client_event(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if client_event is not None:
diff --git a/google/cloud/talent_v4/services/event_service/client.py b/google/cloud/talent_v4/services/event_service/client.py
index 06f1fd4f..df5da227 100644
--- a/google/cloud/talent_v4/services/event_service/client.py
+++ b/google/cloud/talent_v4/services/event_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -34,8 +32,7 @@
from google.cloud.talent_v4.types import event
from google.cloud.talent_v4.types import event_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import EventServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import EventServiceGrpcTransport
from .transports.grpc_asyncio import EventServiceGrpcAsyncIOTransport
@@ -54,7 +51,7 @@ class EventServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = EventServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[EventServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -77,7 +74,8 @@ class EventServiceClient(metaclass=EventServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -109,10 +107,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ EventServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -121,7 +136,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ EventServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -131,29 +146,30 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> EventServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- EventServiceTransport: The transport used by the client instance.
+ EventServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def tenant_path(project: str, tenant: str,) -> str:
- """Return a fully-qualified tenant string."""
+ """Returns a fully-qualified tenant string."""
return "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@staticmethod
def parse_tenant_path(path: str) -> Dict[str, str]:
- """Parse a tenant path into its component segments."""
+ """Parses a tenant path into its component segments."""
m = re.match(r"^projects/(?P.+?)/tenants/(?P.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -166,7 +182,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -177,7 +193,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -188,7 +204,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -199,7 +215,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -213,12 +229,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, EventServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the event service client.
+ """Instantiates the event service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -226,10 +242,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.EventServiceTransport]): The
+ transport (Union[str, EventServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -265,21 +281,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -291,12 +304,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -311,8 +326,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -322,7 +337,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -346,26 +361,27 @@ def create_client_event(
about self service tools.
Args:
- request (:class:`~.event_service.CreateClientEventRequest`):
+ request (google.cloud.talent_v4.types.CreateClientEventRequest):
The request object. The report event request.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the tenant under which the
event is created.
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- client_event (:class:`~.event.ClientEvent`):
+ client_event (google.cloud.talent_v4.types.ClientEvent):
Required. Events issued when end user
interacts with customer's application
that uses Cloud Talent Solution.
+
This corresponds to the ``client_event`` 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.
@@ -373,7 +389,7 @@ def create_client_event(
sent along with the request as metadata.
Returns:
- ~.event.ClientEvent:
+ google.cloud.talent_v4.types.ClientEvent:
An event issued when an end user
interacts with the application that
implements Cloud Talent Solution.
@@ -402,10 +418,8 @@ def create_client_event(
# there are no flattened fields.
if not isinstance(request, event_service.CreateClientEventRequest):
request = event_service.CreateClientEventRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if client_event is not None:
diff --git a/google/cloud/talent_v4/services/event_service/transports/__init__.py b/google/cloud/talent_v4/services/event_service/transports/__init__.py
index c7dabde5..200c7dae 100644
--- a/google/cloud/talent_v4/services/event_service/transports/__init__.py
+++ b/google/cloud/talent_v4/services/event_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4/services/event_service/transports/base.py b/google/cloud/talent_v4/services/event_service/transports/base.py
index 88f54bbc..7400fc68 100644
--- a/google/cloud/talent_v4/services/event_service/transports/base.py
+++ b/google/cloud/talent_v4/services/event_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,21 +13,22 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.types import event
from google.cloud.talent_v4.types import event_service
-
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution("google-cloud-talent",).version,
@@ -36,6 +36,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class EventServiceTransport(abc.ABC):
"""Abstract transport class for EventService."""
@@ -45,21 +54,25 @@ class EventServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -68,42 +81,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -116,9 +164,9 @@ def _prep_wrapped_messages(self, client_info):
@property
def create_client_event(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[event_service.CreateClientEventRequest],
- typing.Union[event.ClientEvent, typing.Awaitable[event.ClientEvent]],
+ Union[event.ClientEvent, Awaitable[event.ClientEvent]],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4/services/event_service/transports/grpc.py b/google/cloud/talent_v4/services/event_service/transports/grpc.py
index c6dfa670..3a577771 100644
--- a/google/cloud/talent_v4/services/event_service/transports/grpc.py
+++ b/google/cloud/talent_v4/services/event_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,21 +13,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.cloud.talent_v4.types import event
from google.cloud.talent_v4.types import event_service
-
from .base import EventServiceTransport, DEFAULT_CLIENT_INFO
@@ -51,20 +48,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -88,6 +88,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -95,6 +99,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -102,72 +108,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -175,23 +170,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -199,7 +185,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -222,13 +208,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
diff --git a/google/cloud/talent_v4/services/event_service/transports/grpc_asyncio.py b/google/cloud/talent_v4/services/event_service/transports/grpc_asyncio.py
index 38de85b0..48405b66 100644
--- a/google/cloud/talent_v4/services/event_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4/services/event_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,20 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
from google.cloud.talent_v4.types import event
from google.cloud.talent_v4.types import event_service
-
from .base import EventServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import EventServiceGrpcTransport
@@ -54,7 +51,7 @@ class EventServiceGrpcAsyncIOTransport(EventServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -62,7 +59,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -81,13 +78,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -95,20 +94,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -133,13 +135,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -147,72 +155,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -220,17 +216,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
diff --git a/google/cloud/talent_v4/services/job_service/__init__.py b/google/cloud/talent_v4/services/job_service/__init__.py
index 5f157047..3d8d94db 100644
--- a/google/cloud/talent_v4/services/job_service/__init__.py
+++ b/google/cloud/talent_v4/services/job_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import JobServiceClient
from .async_client import JobServiceAsyncClient
diff --git a/google/cloud/talent_v4/services/job_service/async_client.py b/google/cloud/talent_v4/services/job_service/async_client.py
index ec420503..fa14c796 100644
--- a/google/cloud/talent_v4/services/job_service/async_client.py
+++ b/google/cloud/talent_v4/services/job_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,10 +20,10 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.api_core import operation # type: ignore
@@ -36,9 +34,8 @@
from google.cloud.talent_v4.types import job
from google.cloud.talent_v4.types import job as gct_job
from google.cloud.talent_v4.types import job_service
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import JobServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import JobServiceGrpcAsyncIOTransport
from .client import JobServiceClient
@@ -60,36 +57,61 @@ class JobServiceAsyncClient:
parse_job_path = staticmethod(JobServiceClient.parse_job_path)
tenant_path = staticmethod(JobServiceClient.tenant_path)
parse_tenant_path = staticmethod(JobServiceClient.parse_tenant_path)
-
common_billing_account_path = staticmethod(
JobServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
JobServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(JobServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(JobServiceClient.parse_common_folder_path)
-
common_organization_path = staticmethod(JobServiceClient.common_organization_path)
parse_common_organization_path = staticmethod(
JobServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(JobServiceClient.common_project_path)
parse_common_project_path = staticmethod(JobServiceClient.parse_common_project_path)
-
common_location_path = staticmethod(JobServiceClient.common_location_path)
parse_common_location_path = staticmethod(
JobServiceClient.parse_common_location_path
)
- from_service_account_file = JobServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ JobServiceAsyncClient: The constructed client.
+ """
+ return JobServiceClient.from_service_account_info.__func__(JobServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ JobServiceAsyncClient: The constructed client.
+ """
+ return JobServiceClient.from_service_account_file.__func__(JobServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> JobServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
JobServiceTransport: The transport used by the client instance.
@@ -103,12 +125,12 @@ def transport(self) -> JobServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, JobServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the job service client.
+ """Instantiates the job service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -140,7 +162,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = JobServiceClient(
credentials=credentials,
transport=transport,
@@ -163,7 +184,7 @@ async def create_job(
but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.CreateJobRequest`):
+ request (:class:`google.cloud.talent_v4.types.CreateJobRequest`):
The request object. Create job request.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -172,15 +193,15 @@ async def create_job(
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- job (:class:`~.gct_job.Job`):
+ job (:class:`google.cloud.talent_v4.types.Job`):
Required. The Job to be created.
This corresponds to the ``job`` 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.
@@ -188,11 +209,11 @@ async def create_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a [Company][google.cloud.talent.v4.Company],
- which is the hiring entity responsible for the job.
+ google.cloud.talent_v4.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4.Company], which is
+ the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -209,7 +230,6 @@ async def create_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if job is not None:
@@ -248,7 +268,7 @@ async def batch_create_jobs(
r"""Begins executing a batch create jobs operation.
Args:
- request (:class:`~.job_service.BatchCreateJobsRequest`):
+ request (:class:`google.cloud.talent_v4.types.BatchCreateJobsRequest`):
The request object. Request to create a batch of jobs.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -257,17 +277,18 @@ async def batch_create_jobs(
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (:class:`Sequence[google.cloud.talent_v4.types.Job]`):
Required. The jobs to be created.
A maximum of 200 jobs can be created in
a batch.
+
This corresponds to the ``jobs`` 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.
@@ -275,16 +296,13 @@ async def batch_create_jobs(
sent along with the request as metadata.
Returns:
- ~.operation_async.AsyncOperation:
+ google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.BatchCreateJobsResponse``: The
- result of
- [JobService.BatchCreateJobs][google.cloud.talent.v4.JobService.BatchCreateJobs].
- It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4.types.BatchCreateJobsResponse` The result of [JobService.BatchCreateJobs][google.cloud.talent.v4.JobService.BatchCreateJobs]. It's used to
+ replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -301,10 +319,8 @@ async def batch_create_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
if jobs:
request.jobs.extend(jobs)
@@ -349,7 +365,7 @@ async def get_job(
recently EXPIRED within the last 90 days.
Args:
- request (:class:`~.job_service.GetJobRequest`):
+ request (:class:`google.cloud.talent_v4.types.GetJobRequest`):
The request object. Get job request.
name (:class:`str`):
Required. The resource name of the job to retrieve.
@@ -357,10 +373,10 @@ async def get_job(
The format is
"projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}".
For example, "projects/foo/tenants/bar/jobs/baz".
+
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.
@@ -368,11 +384,11 @@ async def get_job(
sent along with the request as metadata.
Returns:
- ~.job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a [Company][google.cloud.talent.v4.Company],
- which is the hiring entity responsible for the job.
+ google.cloud.talent_v4.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4.Company], which is
+ the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -389,7 +405,6 @@ async def get_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -402,8 +417,10 @@ async def get_job(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -426,7 +443,7 @@ async def update_job(
request: job_service.UpdateJobRequest = None,
*,
job: gct_job.Job = None,
- update_mask: field_mask.FieldMask = None,
+ update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
@@ -437,14 +454,14 @@ async def update_job(
minutes.
Args:
- request (:class:`~.job_service.UpdateJobRequest`):
+ request (:class:`google.cloud.talent_v4.types.UpdateJobRequest`):
The request object. Update job request.
- job (:class:`~.gct_job.Job`):
+ job (:class:`google.cloud.talent_v4.types.Job`):
Required. The Job to be updated.
This corresponds to the ``job`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- update_mask (:class:`~.field_mask.FieldMask`):
+ update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
Strongly recommended for the best service experience.
If
@@ -456,10 +473,10 @@ async def update_job(
A field mask to restrict the fields that are updated.
Only top level fields of
[Job][google.cloud.talent.v4.Job] are supported.
+
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.
@@ -467,11 +484,11 @@ async def update_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a [Company][google.cloud.talent.v4.Company],
- which is the hiring entity responsible for the job.
+ google.cloud.talent_v4.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4.Company], which is
+ the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -488,7 +505,6 @@ async def update_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if job is not None:
request.job = job
if update_mask is not None:
@@ -527,7 +543,7 @@ async def batch_update_jobs(
r"""Begins executing a batch update jobs operation.
Args:
- request (:class:`~.job_service.BatchUpdateJobsRequest`):
+ request (:class:`google.cloud.talent_v4.types.BatchUpdateJobsRequest`):
The request object. Request to update a batch of jobs.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -536,17 +552,18 @@ async def batch_update_jobs(
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (:class:`Sequence[google.cloud.talent_v4.types.Job]`):
Required. The jobs to be updated.
A maximum of 200 jobs can be updated in
a batch.
+
This corresponds to the ``jobs`` 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.
@@ -554,16 +571,13 @@ async def batch_update_jobs(
sent along with the request as metadata.
Returns:
- ~.operation_async.AsyncOperation:
+ google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.BatchUpdateJobsResponse``: The
- result of
- [JobService.BatchUpdateJobs][google.cloud.talent.v4.JobService.BatchUpdateJobs].
- It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4.types.BatchUpdateJobsResponse` The result of [JobService.BatchUpdateJobs][google.cloud.talent.v4.JobService.BatchUpdateJobs]. It's used to
+ replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -580,10 +594,8 @@ async def batch_update_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
if jobs:
request.jobs.extend(jobs)
@@ -629,7 +641,7 @@ async def delete_job(
seconds, but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.DeleteJobRequest`):
+ request (:class:`google.cloud.talent_v4.types.DeleteJobRequest`):
The request object. Delete job request.
name (:class:`str`):
Required. The resource name of the job to be deleted.
@@ -637,10 +649,10 @@ async def delete_job(
The format is
"projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}".
For example, "projects/foo/tenants/bar/jobs/baz".
+
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.
@@ -661,7 +673,6 @@ async def delete_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -674,8 +685,10 @@ async def delete_job(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -705,7 +718,7 @@ async def batch_delete_jobs(
r"""Begins executing a batch delete jobs operation.
Args:
- request (:class:`~.job_service.BatchDeleteJobsRequest`):
+ request (:class:`google.cloud.talent_v4.types.BatchDeleteJobsRequest`):
The request object. Request to delete a batch of jobs.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -717,6 +730,7 @@ async def batch_delete_jobs(
The parent of all of the jobs specified in ``names``
must match this field.
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -728,10 +742,10 @@ async def batch_delete_jobs(
For example, "projects/foo/tenants/bar/jobs/baz".
A maximum of 200 jobs can be deleted in a batch.
+
This corresponds to the ``names`` 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.
@@ -739,16 +753,13 @@ async def batch_delete_jobs(
sent along with the request as metadata.
Returns:
- ~.operation_async.AsyncOperation:
+ google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.BatchDeleteJobsResponse``: The
- result of
- [JobService.BatchDeleteJobs][google.cloud.talent.v4.JobService.BatchDeleteJobs].
- It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4.types.BatchDeleteJobsResponse` The result of [JobService.BatchDeleteJobs][google.cloud.talent.v4.JobService.BatchDeleteJobs]. It's used to
+ replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -765,10 +776,8 @@ async def batch_delete_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
if names:
request.names.extend(names)
@@ -813,7 +822,7 @@ async def list_jobs(
r"""Lists jobs by filter.
Args:
- request (:class:`~.job_service.ListJobsRequest`):
+ request (:class:`google.cloud.talent_v4.types.ListJobsRequest`):
The request object. List jobs request.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -822,6 +831,7 @@ async def list_jobs(
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -847,11 +857,11 @@ async def list_jobs(
requisitionId = "req-1"
- companyName =
"projects/foo/tenants/bar/companies/baz" AND status =
- "EXPIRED".
+ "EXPIRED"
+
This corresponds to the ``filter`` 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.
@@ -859,7 +869,7 @@ async def list_jobs(
sent along with the request as metadata.
Returns:
- ~.pagers.ListJobsAsyncPager:
+ google.cloud.talent_v4.services.job_service.pagers.ListJobsAsyncPager:
List jobs response.
Iterating over this object will yield
results and resolve additional pages
@@ -880,7 +890,6 @@ async def list_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if filter is not None:
@@ -895,8 +904,10 @@ async def list_jobs(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -937,10 +948,9 @@ async def search_jobs(
has permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (:class:`google.cloud.talent_v4.types.SearchJobsRequest`):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -948,11 +958,10 @@ async def search_jobs(
sent along with the request as metadata.
Returns:
- ~.job_service.SearchJobsResponse:
+ google.cloud.talent_v4.types.SearchJobsResponse:
Response for SearchJob method.
"""
# Create or coerce a protobuf request object.
-
request = job_service.SearchJobsRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
@@ -998,10 +1007,9 @@ async def search_jobs_for_alert(
permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (:class:`google.cloud.talent_v4.types.SearchJobsRequest`):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -1009,11 +1017,10 @@ async def search_jobs_for_alert(
sent along with the request as metadata.
Returns:
- ~.job_service.SearchJobsResponse:
+ google.cloud.talent_v4.types.SearchJobsResponse:
Response for SearchJob method.
"""
# Create or coerce a protobuf request object.
-
request = job_service.SearchJobsRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
diff --git a/google/cloud/talent_v4/services/job_service/client.py b/google/cloud/talent_v4/services/job_service/client.py
index 0e8ec2b0..3bd85dc5 100644
--- a/google/cloud/talent_v4/services/job_service/client.py
+++ b/google/cloud/talent_v4/services/job_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -40,9 +38,8 @@
from google.cloud.talent_v4.types import job
from google.cloud.talent_v4.types import job as gct_job
from google.cloud.talent_v4.types import job_service
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import JobServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import JobServiceGrpcTransport
from .transports.grpc_asyncio import JobServiceGrpcAsyncIOTransport
@@ -61,7 +58,7 @@ class JobServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = JobServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[JobServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -86,7 +83,8 @@ class JobServiceClient(metaclass=JobServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -118,10 +116,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ JobServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -130,7 +145,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ JobServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -140,23 +155,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> JobServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- JobServiceTransport: The transport used by the client instance.
+ JobServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -165,14 +181,14 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def job_path(project: str, tenant: str, job: str,) -> str:
- """Return a fully-qualified job string."""
+ """Returns a fully-qualified job string."""
return "projects/{project}/tenants/{tenant}/jobs/{job}".format(
project=project, tenant=tenant, job=job,
)
@staticmethod
def parse_job_path(path: str) -> Dict[str, str]:
- """Parse a job path into its component segments."""
+ """Parses a job path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/jobs/(?P.+?)$",
path,
@@ -181,20 +197,20 @@ def parse_job_path(path: str) -> Dict[str, str]:
@staticmethod
def tenant_path(project: str, tenant: str,) -> str:
- """Return a fully-qualified tenant string."""
+ """Returns a fully-qualified tenant string."""
return "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@staticmethod
def parse_tenant_path(path: str) -> Dict[str, str]:
- """Parse a tenant path into its component segments."""
+ """Parses a tenant path into its component segments."""
m = re.match(r"^projects/(?P.+?)/tenants/(?P.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -207,7 +223,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -218,7 +234,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -229,7 +245,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -240,7 +256,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -254,12 +270,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, JobServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the job service client.
+ """Instantiates the job service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -267,10 +283,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.JobServiceTransport]): The
+ transport (Union[str, JobServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -306,21 +322,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -332,12 +345,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -352,8 +367,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -363,7 +378,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -383,24 +398,24 @@ def create_job(
but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.CreateJobRequest`):
+ request (google.cloud.talent_v4.types.CreateJobRequest):
The request object. Create job request.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- job (:class:`~.gct_job.Job`):
+ job (google.cloud.talent_v4.types.Job):
Required. The Job to be created.
This corresponds to the ``job`` 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.
@@ -408,11 +423,11 @@ def create_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a [Company][google.cloud.talent.v4.Company],
- which is the hiring entity responsible for the job.
+ google.cloud.talent_v4.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4.Company], which is
+ the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -431,10 +446,8 @@ def create_job(
# there are no flattened fields.
if not isinstance(request, job_service.CreateJobRequest):
request = job_service.CreateJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if job is not None:
@@ -469,26 +482,27 @@ def batch_create_jobs(
r"""Begins executing a batch create jobs operation.
Args:
- request (:class:`~.job_service.BatchCreateJobsRequest`):
+ request (google.cloud.talent_v4.types.BatchCreateJobsRequest):
The request object. Request to create a batch of jobs.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (Sequence[google.cloud.talent_v4.types.Job]):
Required. The jobs to be created.
A maximum of 200 jobs can be created in
a batch.
+
This corresponds to the ``jobs`` 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.
@@ -496,16 +510,13 @@ def batch_create_jobs(
sent along with the request as metadata.
Returns:
- ~.operation.Operation:
+ google.api_core.operation.Operation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.BatchCreateJobsResponse``: The
- result of
- [JobService.BatchCreateJobs][google.cloud.talent.v4.JobService.BatchCreateJobs].
- It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4.types.BatchCreateJobsResponse` The result of [JobService.BatchCreateJobs][google.cloud.talent.v4.JobService.BatchCreateJobs]. It's used to
+ replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -524,15 +535,12 @@ def batch_create_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.BatchCreateJobsRequest):
request = job_service.BatchCreateJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
- if jobs:
- request.jobs.extend(jobs)
+ if jobs is not None:
+ request.jobs = jobs
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
@@ -571,18 +579,18 @@ def get_job(
recently EXPIRED within the last 90 days.
Args:
- request (:class:`~.job_service.GetJobRequest`):
+ request (google.cloud.talent_v4.types.GetJobRequest):
The request object. Get job request.
- name (:class:`str`):
+ name (str):
Required. The resource name of the job to retrieve.
The format is
"projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}".
For example, "projects/foo/tenants/bar/jobs/baz".
+
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.
@@ -590,11 +598,11 @@ def get_job(
sent along with the request as metadata.
Returns:
- ~.job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a [Company][google.cloud.talent.v4.Company],
- which is the hiring entity responsible for the job.
+ google.cloud.talent_v4.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4.Company], which is
+ the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -613,10 +621,8 @@ def get_job(
# there are no flattened fields.
if not isinstance(request, job_service.GetJobRequest):
request = job_service.GetJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -641,7 +647,7 @@ def update_job(
request: job_service.UpdateJobRequest = None,
*,
job: gct_job.Job = None,
- update_mask: field_mask.FieldMask = None,
+ update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
@@ -652,14 +658,14 @@ def update_job(
minutes.
Args:
- request (:class:`~.job_service.UpdateJobRequest`):
+ request (google.cloud.talent_v4.types.UpdateJobRequest):
The request object. Update job request.
- job (:class:`~.gct_job.Job`):
+ job (google.cloud.talent_v4.types.Job):
Required. The Job to be updated.
This corresponds to the ``job`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- update_mask (:class:`~.field_mask.FieldMask`):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -671,10 +677,10 @@ def update_job(
A field mask to restrict the fields that are updated.
Only top level fields of
[Job][google.cloud.talent.v4.Job] are supported.
+
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.
@@ -682,11 +688,11 @@ def update_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a [Company][google.cloud.talent.v4.Company],
- which is the hiring entity responsible for the job.
+ google.cloud.talent_v4.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4.Company], which is
+ the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -705,10 +711,8 @@ def update_job(
# there are no flattened fields.
if not isinstance(request, job_service.UpdateJobRequest):
request = job_service.UpdateJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if job is not None:
request.job = job
if update_mask is not None:
@@ -743,26 +747,27 @@ def batch_update_jobs(
r"""Begins executing a batch update jobs operation.
Args:
- request (:class:`~.job_service.BatchUpdateJobsRequest`):
+ request (google.cloud.talent_v4.types.BatchUpdateJobsRequest):
The request object. Request to update a batch of jobs.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (Sequence[google.cloud.talent_v4.types.Job]):
Required. The jobs to be updated.
A maximum of 200 jobs can be updated in
a batch.
+
This corresponds to the ``jobs`` 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.
@@ -770,16 +775,13 @@ def batch_update_jobs(
sent along with the request as metadata.
Returns:
- ~.operation.Operation:
+ google.api_core.operation.Operation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.BatchUpdateJobsResponse``: The
- result of
- [JobService.BatchUpdateJobs][google.cloud.talent.v4.JobService.BatchUpdateJobs].
- It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4.types.BatchUpdateJobsResponse` The result of [JobService.BatchUpdateJobs][google.cloud.talent.v4.JobService.BatchUpdateJobs]. It's used to
+ replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -798,15 +800,12 @@ def batch_update_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.BatchUpdateJobsRequest):
request = job_service.BatchUpdateJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
- if jobs:
- request.jobs.extend(jobs)
+ if jobs is not None:
+ request.jobs = jobs
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
@@ -846,18 +845,18 @@ def delete_job(
seconds, but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.DeleteJobRequest`):
+ request (google.cloud.talent_v4.types.DeleteJobRequest):
The request object. Delete job request.
- name (:class:`str`):
+ name (str):
Required. The resource name of the job to be deleted.
The format is
"projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}".
For example, "projects/foo/tenants/bar/jobs/baz".
+
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.
@@ -880,10 +879,8 @@ def delete_job(
# there are no flattened fields.
if not isinstance(request, job_service.DeleteJobRequest):
request = job_service.DeleteJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -915,9 +912,9 @@ def batch_delete_jobs(
r"""Begins executing a batch delete jobs operation.
Args:
- request (:class:`~.job_service.BatchDeleteJobsRequest`):
+ request (google.cloud.talent_v4.types.BatchDeleteJobsRequest):
The request object. Request to delete a batch of jobs.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
@@ -927,10 +924,11 @@ def batch_delete_jobs(
The parent of all of the jobs specified in ``names``
must match this field.
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- names (:class:`Sequence[str]`):
+ names (Sequence[str]):
The names of the jobs to delete.
The format is
@@ -938,10 +936,10 @@ def batch_delete_jobs(
For example, "projects/foo/tenants/bar/jobs/baz".
A maximum of 200 jobs can be deleted in a batch.
+
This corresponds to the ``names`` 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.
@@ -949,16 +947,13 @@ def batch_delete_jobs(
sent along with the request as metadata.
Returns:
- ~.operation.Operation:
+ google.api_core.operation.Operation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.BatchDeleteJobsResponse``: The
- result of
- [JobService.BatchDeleteJobs][google.cloud.talent.v4.JobService.BatchDeleteJobs].
- It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4.types.BatchDeleteJobsResponse` The result of [JobService.BatchDeleteJobs][google.cloud.talent.v4.JobService.BatchDeleteJobs]. It's used to
+ replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -977,15 +972,12 @@ def batch_delete_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.BatchDeleteJobsRequest):
request = job_service.BatchDeleteJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
- if names:
- request.names.extend(names)
+ if names is not None:
+ request.names = names
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
@@ -1024,19 +1016,20 @@ def list_jobs(
r"""Lists jobs by filter.
Args:
- request (:class:`~.job_service.ListJobsRequest`):
+ request (google.cloud.talent_v4.types.ListJobsRequest):
The request object. List jobs request.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- filter (:class:`str`):
+ filter (str):
Required. The filter string specifies the jobs to be
enumerated.
@@ -1058,11 +1051,11 @@ def list_jobs(
requisitionId = "req-1"
- companyName =
"projects/foo/tenants/bar/companies/baz" AND status =
- "EXPIRED".
+ "EXPIRED"
+
This corresponds to the ``filter`` 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.
@@ -1070,7 +1063,7 @@ def list_jobs(
sent along with the request as metadata.
Returns:
- ~.pagers.ListJobsPager:
+ google.cloud.talent_v4.services.job_service.pagers.ListJobsPager:
List jobs response.
Iterating over this object will yield
results and resolve additional pages
@@ -1093,10 +1086,8 @@ def list_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.ListJobsRequest):
request = job_service.ListJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if filter is not None:
@@ -1141,10 +1132,9 @@ def search_jobs(
has permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4.types.SearchJobsRequest):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -1152,11 +1142,10 @@ def search_jobs(
sent along with the request as metadata.
Returns:
- ~.job_service.SearchJobsResponse:
+ google.cloud.talent_v4.types.SearchJobsResponse:
Response for SearchJob method.
"""
# Create or coerce a protobuf request object.
-
# Minor optimization to avoid making a copy if the user passes
# in a job_service.SearchJobsRequest.
# There's no risk of modifying the input as we've already verified
@@ -1203,10 +1192,9 @@ def search_jobs_for_alert(
permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4.types.SearchJobsRequest):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -1214,11 +1202,10 @@ def search_jobs_for_alert(
sent along with the request as metadata.
Returns:
- ~.job_service.SearchJobsResponse:
+ google.cloud.talent_v4.types.SearchJobsResponse:
Response for SearchJob method.
"""
# Create or coerce a protobuf request object.
-
# Minor optimization to avoid making a copy if the user passes
# in a job_service.SearchJobsRequest.
# There's no risk of modifying the input as we've already verified
diff --git a/google/cloud/talent_v4/services/job_service/pagers.py b/google/cloud/talent_v4/services/job_service/pagers.py
index e759d8e3..ec63a7a7 100644
--- a/google/cloud/talent_v4/services/job_service/pagers.py
+++ b/google/cloud/talent_v4/services/job_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4.types import job
from google.cloud.talent_v4.types import job_service
@@ -25,7 +32,7 @@ class ListJobsPager:
"""A pager for iterating through ``list_jobs`` requests.
This class thinly wraps an initial
- :class:`~.job_service.ListJobsResponse` object, and
+ :class:`google.cloud.talent_v4.types.ListJobsResponse` object, and
provides an ``__iter__`` method to iterate through its
``jobs`` field.
@@ -34,7 +41,7 @@ class ListJobsPager:
through the ``jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.ListJobsResponse`
+ All the usual :class:`google.cloud.talent_v4.types.ListJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -52,9 +59,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.ListJobsRequest`):
+ request (google.cloud.talent_v4.types.ListJobsRequest):
The initial request object.
- response (:class:`~.job_service.ListJobsResponse`):
+ response (google.cloud.talent_v4.types.ListJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -87,7 +94,7 @@ class ListJobsAsyncPager:
"""A pager for iterating through ``list_jobs`` requests.
This class thinly wraps an initial
- :class:`~.job_service.ListJobsResponse` object, and
+ :class:`google.cloud.talent_v4.types.ListJobsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``jobs`` field.
@@ -96,7 +103,7 @@ class ListJobsAsyncPager:
through the ``jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.ListJobsResponse`
+ All the usual :class:`google.cloud.talent_v4.types.ListJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -109,14 +116,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.ListJobsRequest`):
+ request (google.cloud.talent_v4.types.ListJobsRequest):
The initial request object.
- response (:class:`~.job_service.ListJobsResponse`):
+ response (google.cloud.talent_v4.types.ListJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4/services/job_service/transports/__init__.py b/google/cloud/talent_v4/services/job_service/transports/__init__.py
index 349bfbcd..c512946d 100644
--- a/google/cloud/talent_v4/services/job_service/transports/__init__.py
+++ b/google/cloud/talent_v4/services/job_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4/services/job_service/transports/base.py b/google/cloud/talent_v4/services/job_service/transports/base.py
index 37a4781f..6e4ab3c0 100644
--- a/google/cloud/talent_v4/services/job_service/transports/base.py
+++ b/google/cloud/talent_v4/services/job_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,24 +13,25 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.api_core import operations_v1 # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.types import job
from google.cloud.talent_v4.types import job as gct_job
from google.cloud.talent_v4.types import job_service
-from google.longrunning import operations_pb2 as operations # type: ignore
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -40,6 +40,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class JobServiceTransport(abc.ABC):
"""Abstract transport class for JobService."""
@@ -49,21 +58,25 @@ class JobServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -72,42 +85,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -125,8 +173,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -144,8 +194,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -160,8 +212,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -184,84 +238,77 @@ def operations_client(self) -> operations_v1.OperationsClient:
@property
def create_job(
self,
- ) -> typing.Callable[
- [job_service.CreateJobRequest],
- typing.Union[gct_job.Job, typing.Awaitable[gct_job.Job]],
+ ) -> Callable[
+ [job_service.CreateJobRequest], Union[gct_job.Job, Awaitable[gct_job.Job]]
]:
raise NotImplementedError()
@property
def batch_create_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.BatchCreateJobsRequest],
- typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def get_job(
self,
- ) -> typing.Callable[
- [job_service.GetJobRequest], typing.Union[job.Job, typing.Awaitable[job.Job]]
- ]:
+ ) -> Callable[[job_service.GetJobRequest], Union[job.Job, Awaitable[job.Job]]]:
raise NotImplementedError()
@property
def update_job(
self,
- ) -> typing.Callable[
- [job_service.UpdateJobRequest],
- typing.Union[gct_job.Job, typing.Awaitable[gct_job.Job]],
+ ) -> Callable[
+ [job_service.UpdateJobRequest], Union[gct_job.Job, Awaitable[gct_job.Job]]
]:
raise NotImplementedError()
@property
def batch_update_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.BatchUpdateJobsRequest],
- typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def delete_job(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.DeleteJobRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def batch_delete_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.BatchDeleteJobsRequest],
- typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def list_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.ListJobsRequest],
- typing.Union[
- job_service.ListJobsResponse, typing.Awaitable[job_service.ListJobsResponse]
- ],
+ Union[job_service.ListJobsResponse, Awaitable[job_service.ListJobsResponse]],
]:
raise NotImplementedError()
@property
def search_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.SearchJobsRequest],
- typing.Union[
- job_service.SearchJobsResponse,
- typing.Awaitable[job_service.SearchJobsResponse],
+ Union[
+ job_service.SearchJobsResponse, Awaitable[job_service.SearchJobsResponse]
],
]:
raise NotImplementedError()
@@ -269,11 +316,10 @@ def search_jobs(
@property
def search_jobs_for_alert(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.SearchJobsRequest],
- typing.Union[
- job_service.SearchJobsResponse,
- typing.Awaitable[job_service.SearchJobsResponse],
+ Union[
+ job_service.SearchJobsResponse, Awaitable[job_service.SearchJobsResponse]
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4/services/job_service/transports/grpc.py b/google/cloud/talent_v4/services/job_service/transports/grpc.py
index 9f8ddd1e..1803ecd1 100644
--- a/google/cloud/talent_v4/services/job_service/transports/grpc.py
+++ b/google/cloud/talent_v4/services/job_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -30,9 +28,8 @@
from google.cloud.talent_v4.types import job
from google.cloud.talent_v4.types import job as gct_job
from google.cloud.talent_v4.types import job_service
-from google.longrunning import operations_pb2 as operations # type: ignore
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
from .base import JobServiceTransport, DEFAULT_CLIENT_INFO
@@ -56,20 +53,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -93,6 +93,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -100,6 +104,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -107,72 +113,62 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+ self._operations_client = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -180,24 +176,14 @@ def __init__(
],
)
- self._stubs = {} # type: Dict[str, Callable]
- self._operations_client = None
-
- # 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -205,7 +191,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -228,13 +214,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -287,7 +275,7 @@ def create_job(self) -> Callable[[job_service.CreateJobRequest], gct_job.Job]:
@property
def batch_create_jobs(
self,
- ) -> Callable[[job_service.BatchCreateJobsRequest], operations.Operation]:
+ ) -> Callable[[job_service.BatchCreateJobsRequest], operations_pb2.Operation]:
r"""Return a callable for the batch create jobs method over gRPC.
Begins executing a batch create jobs operation.
@@ -306,7 +294,7 @@ def batch_create_jobs(
self._stubs["batch_create_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/BatchCreateJobs",
request_serializer=job_service.BatchCreateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_create_jobs"]
@@ -365,7 +353,7 @@ def update_job(self) -> Callable[[job_service.UpdateJobRequest], gct_job.Job]:
@property
def batch_update_jobs(
self,
- ) -> Callable[[job_service.BatchUpdateJobsRequest], operations.Operation]:
+ ) -> Callable[[job_service.BatchUpdateJobsRequest], operations_pb2.Operation]:
r"""Return a callable for the batch update jobs method over gRPC.
Begins executing a batch update jobs operation.
@@ -384,12 +372,12 @@ def batch_update_jobs(
self._stubs["batch_update_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/BatchUpdateJobs",
request_serializer=job_service.BatchUpdateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_update_jobs"]
@property
- def delete_job(self) -> Callable[[job_service.DeleteJobRequest], empty.Empty]:
+ def delete_job(self) -> Callable[[job_service.DeleteJobRequest], empty_pb2.Empty]:
r"""Return a callable for the delete job method over gRPC.
Deletes the specified job.
@@ -410,14 +398,14 @@ def delete_job(self) -> Callable[[job_service.DeleteJobRequest], empty.Empty]:
self._stubs["delete_job"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/DeleteJob",
request_serializer=job_service.DeleteJobRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_job"]
@property
def batch_delete_jobs(
self,
- ) -> Callable[[job_service.BatchDeleteJobsRequest], operations.Operation]:
+ ) -> Callable[[job_service.BatchDeleteJobsRequest], operations_pb2.Operation]:
r"""Return a callable for the batch delete jobs method over gRPC.
Begins executing a batch delete jobs operation.
@@ -436,7 +424,7 @@ def batch_delete_jobs(
self._stubs["batch_delete_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/BatchDeleteJobs",
request_serializer=job_service.BatchDeleteJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_delete_jobs"]
diff --git a/google/cloud/talent_v4/services/job_service/transports/grpc_asyncio.py b/google/cloud/talent_v4/services/job_service/transports/grpc_asyncio.py
index 2a50e03c..c4c98ad9 100644
--- a/google/cloud/talent_v4/services/job_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4/services/job_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,16 +13,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
from google.api_core import operations_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -31,9 +29,8 @@
from google.cloud.talent_v4.types import job
from google.cloud.talent_v4.types import job as gct_job
from google.cloud.talent_v4.types import job_service
-from google.longrunning import operations_pb2 as operations # type: ignore
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
from .base import JobServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import JobServiceGrpcTransport
@@ -59,7 +56,7 @@ class JobServiceGrpcAsyncIOTransport(JobServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -67,7 +64,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -86,13 +83,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -100,20 +99,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -138,13 +140,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -152,72 +160,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+ self._operations_client = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -225,18 +222,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
- self._operations_client = None
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -296,7 +283,7 @@ def create_job(
def batch_create_jobs(
self,
) -> Callable[
- [job_service.BatchCreateJobsRequest], Awaitable[operations.Operation]
+ [job_service.BatchCreateJobsRequest], Awaitable[operations_pb2.Operation]
]:
r"""Return a callable for the batch create jobs method over gRPC.
@@ -316,7 +303,7 @@ def batch_create_jobs(
self._stubs["batch_create_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/BatchCreateJobs",
request_serializer=job_service.BatchCreateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_create_jobs"]
@@ -378,7 +365,7 @@ def update_job(
def batch_update_jobs(
self,
) -> Callable[
- [job_service.BatchUpdateJobsRequest], Awaitable[operations.Operation]
+ [job_service.BatchUpdateJobsRequest], Awaitable[operations_pb2.Operation]
]:
r"""Return a callable for the batch update jobs method over gRPC.
@@ -398,14 +385,14 @@ def batch_update_jobs(
self._stubs["batch_update_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/BatchUpdateJobs",
request_serializer=job_service.BatchUpdateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_update_jobs"]
@property
def delete_job(
self,
- ) -> Callable[[job_service.DeleteJobRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[job_service.DeleteJobRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the delete job method over gRPC.
Deletes the specified job.
@@ -426,7 +413,7 @@ def delete_job(
self._stubs["delete_job"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/DeleteJob",
request_serializer=job_service.DeleteJobRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_job"]
@@ -434,7 +421,7 @@ def delete_job(
def batch_delete_jobs(
self,
) -> Callable[
- [job_service.BatchDeleteJobsRequest], Awaitable[operations.Operation]
+ [job_service.BatchDeleteJobsRequest], Awaitable[operations_pb2.Operation]
]:
r"""Return a callable for the batch delete jobs method over gRPC.
@@ -454,7 +441,7 @@ def batch_delete_jobs(
self._stubs["batch_delete_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.JobService/BatchDeleteJobs",
request_serializer=job_service.BatchDeleteJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_delete_jobs"]
diff --git a/google/cloud/talent_v4/services/tenant_service/__init__.py b/google/cloud/talent_v4/services/tenant_service/__init__.py
index c3e2ad3b..7a508509 100644
--- a/google/cloud/talent_v4/services/tenant_service/__init__.py
+++ b/google/cloud/talent_v4/services/tenant_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import TenantServiceClient
from .async_client import TenantServiceAsyncClient
diff --git a/google/cloud/talent_v4/services/tenant_service/async_client.py b/google/cloud/talent_v4/services/tenant_service/async_client.py
index 07940a99..fd2848b7 100644
--- a/google/cloud/talent_v4/services/tenant_service/async_client.py
+++ b/google/cloud/talent_v4/services/tenant_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,18 +20,17 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.services.tenant_service import pagers
from google.cloud.talent_v4.types import tenant
from google.cloud.talent_v4.types import tenant as gct_tenant
from google.cloud.talent_v4.types import tenant_service
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-
+from google.protobuf import field_mask_pb2 # type: ignore
from .transports.base import TenantServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import TenantServiceGrpcAsyncIOTransport
from .client import TenantServiceClient
@@ -51,42 +48,67 @@ class TenantServiceAsyncClient:
tenant_path = staticmethod(TenantServiceClient.tenant_path)
parse_tenant_path = staticmethod(TenantServiceClient.parse_tenant_path)
-
common_billing_account_path = staticmethod(
TenantServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
TenantServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(TenantServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(
TenantServiceClient.parse_common_folder_path
)
-
common_organization_path = staticmethod(
TenantServiceClient.common_organization_path
)
parse_common_organization_path = staticmethod(
TenantServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(TenantServiceClient.common_project_path)
parse_common_project_path = staticmethod(
TenantServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(TenantServiceClient.common_location_path)
parse_common_location_path = staticmethod(
TenantServiceClient.parse_common_location_path
)
- from_service_account_file = TenantServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ TenantServiceAsyncClient: The constructed client.
+ """
+ return TenantServiceClient.from_service_account_info.__func__(TenantServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ TenantServiceAsyncClient: The constructed client.
+ """
+ return TenantServiceClient.from_service_account_file.__func__(TenantServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> TenantServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
TenantServiceTransport: The transport used by the client instance.
@@ -100,12 +122,12 @@ def transport(self) -> TenantServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, TenantServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the tenant service client.
+ """Instantiates the tenant service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -137,7 +159,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = TenantServiceClient(
credentials=credentials,
transport=transport,
@@ -158,7 +179,7 @@ async def create_tenant(
r"""Creates a new tenant entity.
Args:
- request (:class:`~.tenant_service.CreateTenantRequest`):
+ request (:class:`google.cloud.talent_v4.types.CreateTenantRequest`):
The request object. The Request of the CreateTenant
method.
parent (:class:`str`):
@@ -167,15 +188,15 @@ async def create_tenant(
The format is "projects/{project_id}", for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (:class:`google.cloud.talent_v4.types.Tenant`):
Required. The tenant to be created.
This corresponds to the ``tenant`` 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.
@@ -183,7 +204,7 @@ async def create_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -207,7 +228,6 @@ async def create_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if tenant is not None:
@@ -245,7 +265,7 @@ async def get_tenant(
r"""Retrieves specified tenant.
Args:
- request (:class:`~.tenant_service.GetTenantRequest`):
+ request (:class:`google.cloud.talent_v4.types.GetTenantRequest`):
The request object. Request for getting a tenant by
name.
name (:class:`str`):
@@ -255,10 +275,10 @@ async def get_tenant(
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -266,7 +286,7 @@ async def get_tenant(
sent along with the request as metadata.
Returns:
- ~.tenant.Tenant:
+ google.cloud.talent_v4.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -290,7 +310,6 @@ async def get_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -303,8 +322,10 @@ async def get_tenant(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -327,7 +348,7 @@ async def update_tenant(
request: tenant_service.UpdateTenantRequest = None,
*,
tenant: gct_tenant.Tenant = None,
- update_mask: field_mask.FieldMask = None,
+ update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
@@ -335,17 +356,18 @@ async def update_tenant(
r"""Updates specified tenant.
Args:
- request (:class:`~.tenant_service.UpdateTenantRequest`):
+ request (:class:`google.cloud.talent_v4.types.UpdateTenantRequest`):
The request object. Request for updating a specified
tenant.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (:class:`google.cloud.talent_v4.types.Tenant`):
Required. The tenant resource to
replace the current resource in the
system.
+
This corresponds to the ``tenant`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- update_mask (:class:`~.field_mask.FieldMask`):
+ update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
Strongly recommended for the best service experience.
If
@@ -357,10 +379,10 @@ async def update_tenant(
A field mask to specify the tenant fields to be updated.
Only top level fields of
[Tenant][google.cloud.talent.v4.Tenant] are supported.
+
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.
@@ -368,7 +390,7 @@ async def update_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -392,7 +414,6 @@ async def update_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if tenant is not None:
request.tenant = tenant
if update_mask is not None:
@@ -432,7 +453,7 @@ async def delete_tenant(
r"""Deletes specified tenant.
Args:
- request (:class:`~.tenant_service.DeleteTenantRequest`):
+ request (:class:`google.cloud.talent_v4.types.DeleteTenantRequest`):
The request object. Request to delete a tenant.
name (:class:`str`):
Required. The resource name of the tenant to be deleted.
@@ -440,10 +461,10 @@ async def delete_tenant(
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -464,7 +485,6 @@ async def delete_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -477,8 +497,10 @@ async def delete_tenant(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -507,7 +529,7 @@ async def list_tenants(
r"""Lists all tenants associated with the project.
Args:
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (:class:`google.cloud.talent_v4.types.ListTenantsRequest`):
The request object. List tenants for which the client
has ACL visibility.
parent (:class:`str`):
@@ -516,10 +538,10 @@ async def list_tenants(
The format is "projects/{project_id}", for example,
"projects/foo".
+
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.
@@ -527,7 +549,7 @@ async def list_tenants(
sent along with the request as metadata.
Returns:
- ~.pagers.ListTenantsAsyncPager:
+ google.cloud.talent_v4.services.tenant_service.pagers.ListTenantsAsyncPager:
The List tenants response object.
Iterating over this object will yield
results and resolve additional pages
@@ -548,7 +570,6 @@ async def list_tenants(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
@@ -561,8 +582,10 @@ async def list_tenants(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
diff --git a/google/cloud/talent_v4/services/tenant_service/client.py b/google/cloud/talent_v4/services/tenant_service/client.py
index 7492a9c3..e4374c0e 100644
--- a/google/cloud/talent_v4/services/tenant_service/client.py
+++ b/google/cloud/talent_v4/services/tenant_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -36,8 +34,7 @@
from google.cloud.talent_v4.types import tenant
from google.cloud.talent_v4.types import tenant as gct_tenant
from google.cloud.talent_v4.types import tenant_service
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-
+from google.protobuf import field_mask_pb2 # type: ignore
from .transports.base import TenantServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import TenantServiceGrpcTransport
from .transports.grpc_asyncio import TenantServiceGrpcAsyncIOTransport
@@ -56,7 +53,7 @@ class TenantServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = TenantServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[TenantServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -81,7 +78,8 @@ class TenantServiceClient(metaclass=TenantServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -113,10 +111,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ TenantServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -125,7 +140,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ TenantServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -135,29 +150,30 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> TenantServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- TenantServiceTransport: The transport used by the client instance.
+ TenantServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def tenant_path(project: str, tenant: str,) -> str:
- """Return a fully-qualified tenant string."""
+ """Returns a fully-qualified tenant string."""
return "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@staticmethod
def parse_tenant_path(path: str) -> Dict[str, str]:
- """Parse a tenant path into its component segments."""
+ """Parses a tenant path into its component segments."""
m = re.match(r"^projects/(?P.+?)/tenants/(?P.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -170,7 +186,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -181,7 +197,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -192,7 +208,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -203,7 +219,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -217,12 +233,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, TenantServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the tenant service client.
+ """Instantiates the tenant service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -230,10 +246,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.TenantServiceTransport]): The
+ transport (Union[str, TenantServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -269,21 +285,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -295,12 +308,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -315,8 +330,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -326,7 +341,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -344,24 +359,24 @@ def create_tenant(
r"""Creates a new tenant entity.
Args:
- request (:class:`~.tenant_service.CreateTenantRequest`):
+ request (google.cloud.talent_v4.types.CreateTenantRequest):
The request object. The Request of the CreateTenant
method.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the project under which the
tenant is created.
The format is "projects/{project_id}", for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (google.cloud.talent_v4.types.Tenant):
Required. The tenant to be created.
This corresponds to the ``tenant`` 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.
@@ -369,7 +384,7 @@ def create_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -395,10 +410,8 @@ def create_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.CreateTenantRequest):
request = tenant_service.CreateTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if tenant is not None:
@@ -432,20 +445,20 @@ def get_tenant(
r"""Retrieves specified tenant.
Args:
- request (:class:`~.tenant_service.GetTenantRequest`):
+ request (google.cloud.talent_v4.types.GetTenantRequest):
The request object. Request for getting a tenant by
name.
- name (:class:`str`):
+ name (str):
Required. The resource name of the tenant to be
retrieved.
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -453,7 +466,7 @@ def get_tenant(
sent along with the request as metadata.
Returns:
- ~.tenant.Tenant:
+ google.cloud.talent_v4.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -479,10 +492,8 @@ def get_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.GetTenantRequest):
request = tenant_service.GetTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -507,7 +518,7 @@ def update_tenant(
request: tenant_service.UpdateTenantRequest = None,
*,
tenant: gct_tenant.Tenant = None,
- update_mask: field_mask.FieldMask = None,
+ update_mask: field_mask_pb2.FieldMask = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
@@ -515,17 +526,18 @@ def update_tenant(
r"""Updates specified tenant.
Args:
- request (:class:`~.tenant_service.UpdateTenantRequest`):
+ request (google.cloud.talent_v4.types.UpdateTenantRequest):
The request object. Request for updating a specified
tenant.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (google.cloud.talent_v4.types.Tenant):
Required. The tenant resource to
replace the current resource in the
system.
+
This corresponds to the ``tenant`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- update_mask (:class:`~.field_mask.FieldMask`):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -537,10 +549,10 @@ def update_tenant(
A field mask to specify the tenant fields to be updated.
Only top level fields of
[Tenant][google.cloud.talent.v4.Tenant] are supported.
+
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.
@@ -548,7 +560,7 @@ def update_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -574,10 +586,8 @@ def update_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.UpdateTenantRequest):
request = tenant_service.UpdateTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if tenant is not None:
request.tenant = tenant
if update_mask is not None:
@@ -613,18 +623,18 @@ def delete_tenant(
r"""Deletes specified tenant.
Args:
- request (:class:`~.tenant_service.DeleteTenantRequest`):
+ request (google.cloud.talent_v4.types.DeleteTenantRequest):
The request object. Request to delete a tenant.
- name (:class:`str`):
+ name (str):
Required. The resource name of the tenant to be deleted.
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -647,10 +657,8 @@ def delete_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.DeleteTenantRequest):
request = tenant_service.DeleteTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -681,19 +689,19 @@ def list_tenants(
r"""Lists all tenants associated with the project.
Args:
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (google.cloud.talent_v4.types.ListTenantsRequest):
The request object. List tenants for which the client
has ACL visibility.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the project under which the
tenant is created.
The format is "projects/{project_id}", for example,
"projects/foo".
+
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.
@@ -701,7 +709,7 @@ def list_tenants(
sent along with the request as metadata.
Returns:
- ~.pagers.ListTenantsPager:
+ google.cloud.talent_v4.services.tenant_service.pagers.ListTenantsPager:
The List tenants response object.
Iterating over this object will yield
results and resolve additional pages
@@ -724,10 +732,8 @@ def list_tenants(
# there are no flattened fields.
if not isinstance(request, tenant_service.ListTenantsRequest):
request = tenant_service.ListTenantsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
diff --git a/google/cloud/talent_v4/services/tenant_service/pagers.py b/google/cloud/talent_v4/services/tenant_service/pagers.py
index d671fdb7..906d2ce6 100644
--- a/google/cloud/talent_v4/services/tenant_service/pagers.py
+++ b/google/cloud/talent_v4/services/tenant_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4.types import tenant
from google.cloud.talent_v4.types import tenant_service
@@ -25,7 +32,7 @@ class ListTenantsPager:
"""A pager for iterating through ``list_tenants`` requests.
This class thinly wraps an initial
- :class:`~.tenant_service.ListTenantsResponse` object, and
+ :class:`google.cloud.talent_v4.types.ListTenantsResponse` object, and
provides an ``__iter__`` method to iterate through its
``tenants`` field.
@@ -34,7 +41,7 @@ class ListTenantsPager:
through the ``tenants`` field on the
corresponding responses.
- All the usual :class:`~.tenant_service.ListTenantsResponse`
+ All the usual :class:`google.cloud.talent_v4.types.ListTenantsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -52,9 +59,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (google.cloud.talent_v4.types.ListTenantsRequest):
The initial request object.
- response (:class:`~.tenant_service.ListTenantsResponse`):
+ response (google.cloud.talent_v4.types.ListTenantsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -87,7 +94,7 @@ class ListTenantsAsyncPager:
"""A pager for iterating through ``list_tenants`` requests.
This class thinly wraps an initial
- :class:`~.tenant_service.ListTenantsResponse` object, and
+ :class:`google.cloud.talent_v4.types.ListTenantsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``tenants`` field.
@@ -96,7 +103,7 @@ class ListTenantsAsyncPager:
through the ``tenants`` field on the
corresponding responses.
- All the usual :class:`~.tenant_service.ListTenantsResponse`
+ All the usual :class:`google.cloud.talent_v4.types.ListTenantsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -109,14 +116,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (google.cloud.talent_v4.types.ListTenantsRequest):
The initial request object.
- response (:class:`~.tenant_service.ListTenantsResponse`):
+ response (google.cloud.talent_v4.types.ListTenantsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4/services/tenant_service/transports/__init__.py b/google/cloud/talent_v4/services/tenant_service/transports/__init__.py
index 27334b26..663ba19e 100644
--- a/google/cloud/talent_v4/services/tenant_service/transports/__init__.py
+++ b/google/cloud/talent_v4/services/tenant_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4/services/tenant_service/transports/base.py b/google/cloud/talent_v4/services/tenant_service/transports/base.py
index dee8e4f0..1ac777a7 100644
--- a/google/cloud/talent_v4/services/tenant_service/transports/base.py
+++ b/google/cloud/talent_v4/services/tenant_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4.types import tenant
from google.cloud.talent_v4.types import tenant as gct_tenant
from google.cloud.talent_v4.types import tenant_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -38,6 +38,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class TenantServiceTransport(abc.ABC):
"""Abstract transport class for TenantService."""
@@ -47,21 +56,25 @@ class TenantServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -70,42 +83,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -120,8 +168,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -136,8 +186,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -149,8 +201,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -160,47 +214,47 @@ def _prep_wrapped_messages(self, client_info):
@property
def create_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.CreateTenantRequest],
- typing.Union[gct_tenant.Tenant, typing.Awaitable[gct_tenant.Tenant]],
+ Union[gct_tenant.Tenant, Awaitable[gct_tenant.Tenant]],
]:
raise NotImplementedError()
@property
def get_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.GetTenantRequest],
- typing.Union[tenant.Tenant, typing.Awaitable[tenant.Tenant]],
+ Union[tenant.Tenant, Awaitable[tenant.Tenant]],
]:
raise NotImplementedError()
@property
def update_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.UpdateTenantRequest],
- typing.Union[gct_tenant.Tenant, typing.Awaitable[gct_tenant.Tenant]],
+ Union[gct_tenant.Tenant, Awaitable[gct_tenant.Tenant]],
]:
raise NotImplementedError()
@property
def delete_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.DeleteTenantRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_tenants(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.ListTenantsRequest],
- typing.Union[
+ Union[
tenant_service.ListTenantsResponse,
- typing.Awaitable[tenant_service.ListTenantsResponse],
+ Awaitable[tenant_service.ListTenantsResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4/services/tenant_service/transports/grpc.py b/google/cloud/talent_v4/services/tenant_service/transports/grpc.py
index f6ff6185..4dc57d85 100644
--- a/google/cloud/talent_v4/services/tenant_service/transports/grpc.py
+++ b/google/cloud/talent_v4/services/tenant_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -29,8 +27,7 @@
from google.cloud.talent_v4.types import tenant
from google.cloud.talent_v4.types import tenant as gct_tenant
from google.cloud.talent_v4.types import tenant_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import TenantServiceTransport, DEFAULT_CLIENT_INFO
@@ -54,20 +51,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -91,6 +91,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -98,6 +102,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -105,72 +111,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -178,23 +173,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -202,7 +188,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -225,13 +211,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -320,7 +308,7 @@ def update_tenant(
@property
def delete_tenant(
self,
- ) -> Callable[[tenant_service.DeleteTenantRequest], empty.Empty]:
+ ) -> Callable[[tenant_service.DeleteTenantRequest], empty_pb2.Empty]:
r"""Return a callable for the delete tenant method over gRPC.
Deletes specified tenant.
@@ -339,7 +327,7 @@ def delete_tenant(
self._stubs["delete_tenant"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.TenantService/DeleteTenant",
request_serializer=tenant_service.DeleteTenantRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_tenant"]
diff --git a/google/cloud/talent_v4/services/tenant_service/transports/grpc_asyncio.py b/google/cloud/talent_v4/services/tenant_service/transports/grpc_asyncio.py
index dac79077..ec413046 100644
--- a/google/cloud/talent_v4/services/tenant_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4/services/tenant_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -30,8 +28,7 @@
from google.cloud.talent_v4.types import tenant
from google.cloud.talent_v4.types import tenant as gct_tenant
from google.cloud.talent_v4.types import tenant_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import TenantServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import TenantServiceGrpcTransport
@@ -57,7 +54,7 @@ class TenantServiceGrpcAsyncIOTransport(TenantServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -65,7 +62,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -84,13 +81,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -98,20 +97,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -136,13 +138,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -150,72 +158,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -223,17 +219,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -326,7 +313,7 @@ def update_tenant(
@property
def delete_tenant(
self,
- ) -> Callable[[tenant_service.DeleteTenantRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[tenant_service.DeleteTenantRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the delete tenant method over gRPC.
Deletes specified tenant.
@@ -345,7 +332,7 @@ def delete_tenant(
self._stubs["delete_tenant"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4.TenantService/DeleteTenant",
request_serializer=tenant_service.DeleteTenantRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_tenant"]
diff --git a/google/cloud/talent_v4/types/__init__.py b/google/cloud/talent_v4/types/__init__.py
index faf71c78..45d9d6e9 100644
--- a/google/cloud/talent_v4/types/__init__.py
+++ b/google/cloud/talent_v4/types/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,36 +13,35 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .common import (
- TimestampRange,
+ BatchOperationMetadata,
+ CompensationInfo,
+ CustomAttribute,
+ DeviceInfo,
Location,
RequestMetadata,
ResponseMetadata,
- DeviceInfo,
- CustomAttribute,
SpellingCorrection,
- CompensationInfo,
- BatchOperationMetadata,
+ TimestampRange,
+ CommuteMethod,
CompanySize,
- JobBenefit,
DegreeType,
EmploymentType,
- JobLevel,
+ HtmlSanitization,
+ JobBenefit,
JobCategory,
+ JobLevel,
PostingRegion,
Visibility,
- HtmlSanitization,
- CommuteMethod,
)
from .company import Company
from .company_service import (
CreateCompanyRequest,
- GetCompanyRequest,
- UpdateCompanyRequest,
DeleteCompanyRequest,
+ GetCompanyRequest,
ListCompaniesRequest,
ListCompaniesResponse,
+ UpdateCompanyRequest,
)
from .completion_service import (
CompleteQueryRequest,
@@ -55,10 +53,10 @@
)
from .event_service import CreateClientEventRequest
from .filters import (
+ CommuteFilter,
+ CompensationFilter,
JobQuery,
LocationFilter,
- CompensationFilter,
- CommuteFilter,
)
from .histogram import (
HistogramQuery,
@@ -66,93 +64,93 @@
)
from .job import Job
from .job_service import (
+ BatchCreateJobsRequest,
+ BatchCreateJobsResponse,
+ BatchDeleteJobsRequest,
+ BatchDeleteJobsResponse,
+ BatchUpdateJobsRequest,
+ BatchUpdateJobsResponse,
CreateJobRequest,
- GetJobRequest,
- UpdateJobRequest,
DeleteJobRequest,
+ GetJobRequest,
+ JobResult,
ListJobsRequest,
ListJobsResponse,
SearchJobsRequest,
SearchJobsResponse,
- BatchCreateJobsRequest,
- BatchUpdateJobsRequest,
- BatchDeleteJobsRequest,
- JobResult,
- BatchCreateJobsResponse,
- BatchUpdateJobsResponse,
- BatchDeleteJobsResponse,
+ UpdateJobRequest,
JobView,
)
from .tenant import Tenant
from .tenant_service import (
CreateTenantRequest,
- GetTenantRequest,
- UpdateTenantRequest,
DeleteTenantRequest,
+ GetTenantRequest,
ListTenantsRequest,
ListTenantsResponse,
+ UpdateTenantRequest,
)
__all__ = (
- "TimestampRange",
+ "BatchOperationMetadata",
+ "CompensationInfo",
+ "CustomAttribute",
+ "DeviceInfo",
"Location",
"RequestMetadata",
"ResponseMetadata",
- "DeviceInfo",
- "CustomAttribute",
"SpellingCorrection",
- "CompensationInfo",
- "BatchOperationMetadata",
+ "TimestampRange",
+ "CommuteMethod",
"CompanySize",
- "JobBenefit",
"DegreeType",
"EmploymentType",
- "JobLevel",
+ "HtmlSanitization",
+ "JobBenefit",
"JobCategory",
+ "JobLevel",
"PostingRegion",
"Visibility",
- "HtmlSanitization",
- "CommuteMethod",
"Company",
"CreateCompanyRequest",
- "GetCompanyRequest",
- "UpdateCompanyRequest",
"DeleteCompanyRequest",
+ "GetCompanyRequest",
"ListCompaniesRequest",
"ListCompaniesResponse",
+ "UpdateCompanyRequest",
"CompleteQueryRequest",
"CompleteQueryResponse",
"ClientEvent",
"JobEvent",
"CreateClientEventRequest",
+ "CommuteFilter",
+ "CompensationFilter",
"JobQuery",
"LocationFilter",
- "CompensationFilter",
- "CommuteFilter",
"HistogramQuery",
"HistogramQueryResult",
"Job",
+ "BatchCreateJobsRequest",
+ "BatchCreateJobsResponse",
+ "BatchDeleteJobsRequest",
+ "BatchDeleteJobsResponse",
+ "BatchUpdateJobsRequest",
+ "BatchUpdateJobsResponse",
"CreateJobRequest",
- "GetJobRequest",
- "UpdateJobRequest",
"DeleteJobRequest",
+ "GetJobRequest",
+ "JobResult",
"ListJobsRequest",
"ListJobsResponse",
"SearchJobsRequest",
"SearchJobsResponse",
- "BatchCreateJobsRequest",
- "BatchUpdateJobsRequest",
- "BatchDeleteJobsRequest",
- "JobResult",
- "BatchCreateJobsResponse",
- "BatchUpdateJobsResponse",
- "BatchDeleteJobsResponse",
+ "UpdateJobRequest",
"JobView",
"Tenant",
"CreateTenantRequest",
- "GetTenantRequest",
- "UpdateTenantRequest",
"DeleteTenantRequest",
+ "GetTenantRequest",
"ListTenantsRequest",
"ListTenantsResponse",
+ "UpdateTenantRequest",
)
diff --git a/google/cloud/talent_v4/types/common.py b/google/cloud/talent_v4/types/common.py
index 13b73611..8db18e62 100644
--- a/google/cloud/talent_v4/types/common.py
+++ b/google/cloud/talent_v4/types/common.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import money_pb2 as money # type: ignore
-from google.type import postal_address_pb2 as gt_postal_address # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import money_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -178,6 +175,7 @@ class Visibility(proto.Enum):
r"""Deprecated. All resources are only visible to the owner.
An enum that represents who has view access to the resource.
"""
+ _pb_options = {"deprecated": True}
VISIBILITY_UNSPECIFIED = 0
ACCOUNT_ONLY = 1
SHARED_WITH_GOOGLE = 2
@@ -204,17 +202,15 @@ class CommuteMethod(proto.Enum):
class TimestampRange(proto.Message):
r"""Message representing a period of time between two timestamps.
-
Attributes:
- start_time (~.timestamp.Timestamp):
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
Begin of the period (inclusive).
- end_time (~.timestamp.Timestamp):
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
End of the period (exclusive).
"""
- start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,)
-
- end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+ start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
+ end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
class Location(proto.Message):
@@ -222,7 +218,7 @@ class Location(proto.Message):
information.
Attributes:
- location_type (~.common.Location.LocationType):
+ location_type (google.cloud.talent_v4.types.Location.LocationType):
The type of a location, which corresponds to the address
lines field of
[google.type.PostalAddress][google.type.PostalAddress]. For
@@ -230,13 +226,13 @@ class Location(proto.Message):
[LocationType.NEIGHBORHOOD][google.cloud.talent.v4.Location.LocationType.NEIGHBORHOOD],
and "Kansas City, KS, USA" has a type of
[LocationType.LOCALITY][google.cloud.talent.v4.Location.LocationType.LOCALITY].
- postal_address (~.gt_postal_address.PostalAddress):
+ postal_address (google.type.postal_address_pb2.PostalAddress):
Postal address of the location that includes
human readable information, such as postal
delivery and payments addresses. Given a postal
address, a postal service can deliver items to a
premises, P.O. Box, or other delivery location.
- lat_lng (~.latlng.LatLng):
+ lat_lng (google.type.latlng_pb2.LatLng):
An object representing a latitude/longitude
pair.
radius_miles (float):
@@ -263,14 +259,11 @@ class LocationType(proto.Enum):
STREET_ADDRESS = 10
location_type = proto.Field(proto.ENUM, number=1, enum=LocationType,)
-
postal_address = proto.Field(
- proto.MESSAGE, number=2, message=gt_postal_address.PostalAddress,
+ proto.MESSAGE, number=2, message=postal_address_pb2.PostalAddress,
)
-
- lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng.LatLng,)
-
- radius_miles = proto.Field(proto.DOUBLE, number=4)
+ lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng_pb2.LatLng,)
+ radius_miles = proto.Field(proto.DOUBLE, number=4,)
class RequestMetadata(proto.Message):
@@ -342,19 +335,15 @@ class RequestMetadata(proto.Message):
and
[user_id][google.cloud.talent.v4.RequestMetadata.user_id]
for the best service experience.
- device_info (~.common.DeviceInfo):
+ device_info (google.cloud.talent_v4.types.DeviceInfo):
The type of device used by the job seeker at
the time of the call to the service.
"""
- domain = proto.Field(proto.STRING, number=1)
-
- session_id = proto.Field(proto.STRING, number=2)
-
- user_id = proto.Field(proto.STRING, number=3)
-
- allow_missing_ids = proto.Field(proto.BOOL, number=4)
-
+ domain = proto.Field(proto.STRING, number=1,)
+ session_id = proto.Field(proto.STRING, number=2,)
+ user_id = proto.Field(proto.STRING, number=3,)
+ allow_missing_ids = proto.Field(proto.BOOL, number=4,)
device_info = proto.Field(proto.MESSAGE, number=5, message="DeviceInfo",)
@@ -368,7 +357,7 @@ class ResponseMetadata(proto.Message):
This id is logged for tracking purposes.
"""
- request_id = proto.Field(proto.STRING, number=1)
+ request_id = proto.Field(proto.STRING, number=1,)
class DeviceInfo(proto.Message):
@@ -378,7 +367,7 @@ class DeviceInfo(proto.Message):
devices.
Attributes:
- device_type (~.common.DeviceInfo.DeviceType):
+ device_type (google.cloud.talent_v4.types.DeviceInfo.DeviceType):
Type of the device.
id (str):
A device-specific ID. The ID must be a unique
@@ -399,8 +388,7 @@ class DeviceType(proto.Enum):
OTHER = 6
device_type = proto.Field(proto.ENUM, number=1, enum=DeviceType,)
-
- id = proto.Field(proto.STRING, number=2)
+ id = proto.Field(proto.STRING, number=2,)
class CustomAttribute(proto.Message):
@@ -454,18 +442,14 @@ class CustomAttribute(proto.Message):
Default is false.
"""
- string_values = proto.RepeatedField(proto.STRING, number=1)
-
- long_values = proto.RepeatedField(proto.INT64, number=2)
-
- filterable = proto.Field(proto.BOOL, number=3)
-
- keyword_searchable = proto.Field(proto.BOOL, number=4)
+ string_values = proto.RepeatedField(proto.STRING, number=1,)
+ long_values = proto.RepeatedField(proto.INT64, number=2,)
+ filterable = proto.Field(proto.BOOL, number=3,)
+ keyword_searchable = proto.Field(proto.BOOL, number=4,)
class SpellingCorrection(proto.Message):
r"""Spell check result.
-
Attributes:
corrected (bool):
Indicates if the query was corrected by the
@@ -484,25 +468,22 @@ class SpellingCorrection(proto.Message):
"software engineer".
"""
- corrected = proto.Field(proto.BOOL, number=1)
-
- corrected_text = proto.Field(proto.STRING, number=2)
-
- corrected_html = proto.Field(proto.STRING, number=3)
+ corrected = proto.Field(proto.BOOL, number=1,)
+ corrected_text = proto.Field(proto.STRING, number=2,)
+ corrected_html = proto.Field(proto.STRING, number=3,)
class CompensationInfo(proto.Message):
r"""Job compensation details.
-
Attributes:
- entries (Sequence[~.common.CompensationInfo.CompensationEntry]):
+ entries (Sequence[google.cloud.talent_v4.types.CompensationInfo.CompensationEntry]):
Job compensation information.
At most one entry can be of type
[CompensationInfo.CompensationType.BASE][google.cloud.talent.v4.CompensationInfo.CompensationType.BASE],
which is referred as **base compensation entry** for the
job.
- annualized_base_compensation_range (~.common.CompensationInfo.CompensationRange):
+ annualized_base_compensation_range (google.cloud.talent_v4.types.CompensationInfo.CompensationRange):
Output only. Annualized base compensation range. Computed as
base compensation entry's
[CompensationEntry.amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount]
@@ -512,7 +493,7 @@ class CompensationInfo(proto.Message):
See
[CompensationEntry][google.cloud.talent.v4.CompensationInfo.CompensationEntry]
for explanation on compensation annualization.
- annualized_total_compensation_range (~.common.CompensationInfo.CompensationRange):
+ annualized_total_compensation_range (google.cloud.talent_v4.types.CompensationInfo.CompensationRange):
Output only. Annualized total compensation range. Computed
as all compensation entries'
[CompensationEntry.amount][google.cloud.talent.v4.CompensationInfo.CompensationEntry.amount]
@@ -594,25 +575,25 @@ class CompensationEntry(proto.Message):
[expected_units_per_year][google.cloud.talent.v4.CompensationInfo.CompensationEntry.expected_units_per_year].
Attributes:
- type_ (~.common.CompensationInfo.CompensationType):
+ type_ (google.cloud.talent_v4.types.CompensationInfo.CompensationType):
Compensation type.
Default is
[CompensationType.COMPENSATION_TYPE_UNSPECIFIED][google.cloud.talent.v4.CompensationInfo.CompensationType.COMPENSATION_TYPE_UNSPECIFIED].
- unit (~.common.CompensationInfo.CompensationUnit):
+ unit (google.cloud.talent_v4.types.CompensationInfo.CompensationUnit):
Frequency of the specified amount.
Default is
[CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED][google.cloud.talent.v4.CompensationInfo.CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED].
- amount (~.money.Money):
+ amount (google.type.money_pb2.Money):
Compensation amount.
- range_ (~.common.CompensationInfo.CompensationRange):
+ range_ (google.cloud.talent_v4.types.CompensationInfo.CompensationRange):
Compensation range.
description (str):
Compensation description. For example, could
indicate equity terms or provide additional
context to an estimated bonus.
- expected_units_per_year (~.wrappers.DoubleValue):
+ expected_units_per_year (google.protobuf.wrappers_pb2.DoubleValue):
Expected number of units paid each year. If not specified,
when
[Job.employment_types][google.cloud.talent.v4.Job.employment_types]
@@ -630,54 +611,52 @@ class CompensationEntry(proto.Message):
type_ = proto.Field(
proto.ENUM, number=1, enum="CompensationInfo.CompensationType",
)
-
unit = proto.Field(
proto.ENUM, number=2, enum="CompensationInfo.CompensationUnit",
)
-
amount = proto.Field(
- proto.MESSAGE, number=3, oneof="compensation_amount", message=money.Money,
+ proto.MESSAGE,
+ number=3,
+ oneof="compensation_amount",
+ message=money_pb2.Money,
)
-
range_ = proto.Field(
proto.MESSAGE,
number=4,
oneof="compensation_amount",
message="CompensationInfo.CompensationRange",
)
-
- description = proto.Field(proto.STRING, number=5)
-
+ description = proto.Field(proto.STRING, number=5,)
expected_units_per_year = proto.Field(
- proto.MESSAGE, number=6, message=wrappers.DoubleValue,
+ proto.MESSAGE, number=6, message=wrappers_pb2.DoubleValue,
)
class CompensationRange(proto.Message):
r"""Compensation range.
-
Attributes:
- max_compensation (~.money.Money):
+ max_compensation (google.type.money_pb2.Money):
The maximum amount of compensation. If left empty, the value
is set to a maximal compensation value and the currency code
is set to match the [currency
code][google.type.Money.currency_code] of min_compensation.
- min_compensation (~.money.Money):
+ min_compensation (google.type.money_pb2.Money):
The minimum amount of compensation. If left empty, the value
is set to zero and the currency code is set to match the
[currency code][google.type.Money.currency_code] of
max_compensation.
"""
- max_compensation = proto.Field(proto.MESSAGE, number=2, message=money.Money,)
-
- min_compensation = proto.Field(proto.MESSAGE, number=1, message=money.Money,)
+ max_compensation = proto.Field(
+ proto.MESSAGE, number=2, message=money_pb2.Money,
+ )
+ min_compensation = proto.Field(
+ proto.MESSAGE, number=1, message=money_pb2.Money,
+ )
entries = proto.RepeatedField(proto.MESSAGE, number=1, message=CompensationEntry,)
-
annualized_base_compensation_range = proto.Field(
proto.MESSAGE, number=2, message=CompensationRange,
)
-
annualized_total_compensation_range = proto.Field(
proto.MESSAGE, number=3, message=CompensationRange,
)
@@ -689,7 +668,7 @@ class BatchOperationMetadata(proto.Message):
[google.longrunning.Operation.metadata][google.longrunning.Operation.metadata].
Attributes:
- state (~.common.BatchOperationMetadata.State):
+ state (google.cloud.talent_v4.types.BatchOperationMetadata.State):
The state of a long running operation.
state_description (str):
More detailed information about operation
@@ -701,14 +680,14 @@ class BatchOperationMetadata(proto.Message):
Count of failed item(s) inside an operation.
total_count (int):
Count of total item(s) inside an operation.
- create_time (~.timestamp.Timestamp):
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
The time when the batch operation is created.
- update_time (~.timestamp.Timestamp):
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
The time when the batch operation status is updated. The
metadata and the
[update_time][google.cloud.talent.v4.BatchOperationMetadata.update_time]
is refreshed every minute otherwise cached data is returned.
- end_time (~.timestamp.Timestamp):
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
The time when the batch operation is finished and
[google.longrunning.Operation.done][google.longrunning.Operation.done]
is set to ``true``.
@@ -725,20 +704,13 @@ class State(proto.Enum):
CANCELLED = 6
state = proto.Field(proto.ENUM, number=1, enum=State,)
-
- state_description = proto.Field(proto.STRING, number=2)
-
- success_count = proto.Field(proto.INT32, number=3)
-
- failure_count = proto.Field(proto.INT32, number=4)
-
- total_count = proto.Field(proto.INT32, number=5)
-
- create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,)
-
- update_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,)
-
- end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,)
+ state_description = proto.Field(proto.STRING, number=2,)
+ success_count = proto.Field(proto.INT32, number=3,)
+ failure_count = proto.Field(proto.INT32, number=4,)
+ total_count = proto.Field(proto.INT32, number=5,)
+ create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,)
+ update_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,)
+ end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4/types/company.py b/google/cloud/talent_v4/types/company.py
index 9955928e..ee226018 100644
--- a/google/cloud/talent_v4/types/company.py
+++ b/google/cloud/talent_v4/types/company.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,10 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import common
@@ -48,7 +45,7 @@ class Company(proto.Message):
used to uniquely identify the company.
The maximum number of allowed characters is 255.
- size (~.common.CompanySize):
+ size (google.cloud.talent_v4.types.CompanySize):
The employer's company size.
headquarters_address (str):
The street address of the company's main headquarters, which
@@ -87,7 +84,7 @@ class Company(proto.Message):
search keyword. Custom field values with parenthesis,
brackets and special symbols are not searchable as-is, and
those keyword queries must be surrounded by quotes.
- derived_info (~.company.Company.DerivedInfo):
+ derived_info (google.cloud.talent_v4.types.Company.DerivedInfo):
Output only. Derived details about the
company.
suspended (bool):
@@ -99,9 +96,8 @@ class Company(proto.Message):
class DerivedInfo(proto.Message):
r"""Derived details about the company.
-
Attributes:
- headquarters_location (~.common.Location):
+ headquarters_location (google.cloud.talent_v4.types.Location):
A structured headquarters location of the company, resolved
from
[Company.headquarters_address][google.cloud.talent.v4.Company.headquarters_address]
@@ -112,33 +108,21 @@ class DerivedInfo(proto.Message):
proto.MESSAGE, number=1, message=common.Location,
)
- name = proto.Field(proto.STRING, number=1)
-
- display_name = proto.Field(proto.STRING, number=2)
-
- external_id = proto.Field(proto.STRING, number=3)
-
+ name = proto.Field(proto.STRING, number=1,)
+ display_name = proto.Field(proto.STRING, number=2,)
+ external_id = proto.Field(proto.STRING, number=3,)
size = proto.Field(proto.ENUM, number=4, enum=common.CompanySize,)
-
- headquarters_address = proto.Field(proto.STRING, number=5)
-
- hiring_agency = proto.Field(proto.BOOL, number=6)
-
- eeo_text = proto.Field(proto.STRING, number=7)
-
- website_uri = proto.Field(proto.STRING, number=8)
-
- career_site_uri = proto.Field(proto.STRING, number=9)
-
- image_uri = proto.Field(proto.STRING, number=10)
-
+ headquarters_address = proto.Field(proto.STRING, number=5,)
+ hiring_agency = proto.Field(proto.BOOL, number=6,)
+ eeo_text = proto.Field(proto.STRING, number=7,)
+ website_uri = proto.Field(proto.STRING, number=8,)
+ career_site_uri = proto.Field(proto.STRING, number=9,)
+ image_uri = proto.Field(proto.STRING, number=10,)
keyword_searchable_job_custom_attributes = proto.RepeatedField(
- proto.STRING, number=11
+ proto.STRING, number=11,
)
-
derived_info = proto.Field(proto.MESSAGE, number=12, message=DerivedInfo,)
-
- suspended = proto.Field(proto.BOOL, number=13)
+ suspended = proto.Field(proto.BOOL, number=13,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4/types/company_service.py b/google/cloud/talent_v4/types/company_service.py
index 0e166ef9..c72c2d1e 100644
--- a/google/cloud/talent_v4/types/company_service.py
+++ b/google/cloud/talent_v4/types/company_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,13 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import company as gct_company
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -38,7 +35,6 @@
class CreateCompanyRequest(proto.Message):
r"""The Request of the CreateCompany method.
-
Attributes:
parent (str):
Required. Resource name of the tenant under which the
@@ -46,18 +42,16 @@ class CreateCompanyRequest(proto.Message):
The format is "projects/{project_id}/tenants/{tenant_id}",
for example, "projects/foo/tenants/bar".
- company (~.gct_company.Company):
+ company (google.cloud.talent_v4.types.Company):
Required. The company to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
company = proto.Field(proto.MESSAGE, number=2, message=gct_company.Company,)
class GetCompanyRequest(proto.Message):
r"""Request for getting a company by name.
-
Attributes:
name (str):
Required. The resource name of the company to be retrieved.
@@ -68,17 +62,16 @@ class GetCompanyRequest(proto.Message):
"projects/api-test-project/tenants/foo/companies/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateCompanyRequest(proto.Message):
r"""Request for updating a specified company.
-
Attributes:
- company (~.gct_company.Company):
+ company (google.cloud.talent_v4.types.Company):
Required. The company resource to replace the
current resource in the system.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -93,13 +86,13 @@ class UpdateCompanyRequest(proto.Message):
"""
company = proto.Field(proto.MESSAGE, number=1, message=gct_company.Company,)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteCompanyRequest(proto.Message):
r"""Request to delete a company.
-
Attributes:
name (str):
Required. The resource name of the company to be deleted.
@@ -109,12 +102,11 @@ class DeleteCompanyRequest(proto.Message):
for example, "projects/foo/tenants/bar/companies/baz".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class ListCompaniesRequest(proto.Message):
r"""List companies for which the client has ACL visibility.
-
Attributes:
parent (str):
Required. Resource name of the tenant under which the
@@ -140,24 +132,20 @@ class ListCompaniesRequest(proto.Message):
jobs are returned.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- page_token = proto.Field(proto.STRING, number=2)
-
- page_size = proto.Field(proto.INT32, number=3)
-
- require_open_jobs = proto.Field(proto.BOOL, number=4)
+ parent = proto.Field(proto.STRING, number=1,)
+ page_token = proto.Field(proto.STRING, number=2,)
+ page_size = proto.Field(proto.INT32, number=3,)
+ require_open_jobs = proto.Field(proto.BOOL, number=4,)
class ListCompaniesResponse(proto.Message):
r"""The List companies response object.
-
Attributes:
- companies (Sequence[~.gct_company.Company]):
+ companies (Sequence[google.cloud.talent_v4.types.Company]):
Companies for the current client.
next_page_token (str):
A token to retrieve the next page of results.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
@@ -169,9 +157,7 @@ def raw_page(self):
companies = proto.RepeatedField(
proto.MESSAGE, number=1, message=gct_company.Company,
)
-
- next_page_token = proto.Field(proto.STRING, number=2)
-
+ next_page_token = proto.Field(proto.STRING, number=2,)
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
diff --git a/google/cloud/talent_v4/types/completion_service.py b/google/cloud/talent_v4/types/completion_service.py
index ba2529b2..6cdf1a6a 100644
--- a/google/cloud/talent_v4/types/completion_service.py
+++ b/google/cloud/talent_v4/types/completion_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,10 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import common
@@ -29,7 +26,6 @@
class CompleteQueryRequest(proto.Message):
r"""Auto-complete parameters.
-
Attributes:
tenant (str):
Required. Resource name of tenant the completion is
@@ -57,10 +53,10 @@ class CompleteQueryRequest(proto.Message):
The format is
"projects/{project_id}/tenants/{tenant_id}/companies/{company_id}",
for example, "projects/foo/tenants/bar/companies/baz".
- scope (~.completion_service.CompleteQueryRequest.CompletionScope):
+ scope (google.cloud.talent_v4.types.CompleteQueryRequest.CompletionScope):
The scope of the completion. The defaults is
[CompletionScope.PUBLIC][google.cloud.talent.v4.CompleteQueryRequest.CompletionScope.PUBLIC].
- type_ (~.completion_service.CompleteQueryRequest.CompletionType):
+ type_ (google.cloud.talent_v4.types.CompleteQueryRequest.CompletionType):
The completion topic. The default is
[CompletionType.COMBINED][google.cloud.talent.v4.CompleteQueryRequest.CompletionType.COMBINED].
"""
@@ -78,58 +74,47 @@ class CompletionType(proto.Enum):
COMPANY_NAME = 2
COMBINED = 3
- tenant = proto.Field(proto.STRING, number=1)
-
- query = proto.Field(proto.STRING, number=2)
-
- language_codes = proto.RepeatedField(proto.STRING, number=3)
-
- page_size = proto.Field(proto.INT32, number=4)
-
- company = proto.Field(proto.STRING, number=5)
-
+ tenant = proto.Field(proto.STRING, number=1,)
+ query = proto.Field(proto.STRING, number=2,)
+ language_codes = proto.RepeatedField(proto.STRING, number=3,)
+ page_size = proto.Field(proto.INT32, number=4,)
+ company = proto.Field(proto.STRING, number=5,)
scope = proto.Field(proto.ENUM, number=6, enum=CompletionScope,)
-
type_ = proto.Field(proto.ENUM, number=7, enum=CompletionType,)
class CompleteQueryResponse(proto.Message):
r"""Response of auto-complete query.
-
Attributes:
- completion_results (Sequence[~.completion_service.CompleteQueryResponse.CompletionResult]):
+ completion_results (Sequence[google.cloud.talent_v4.types.CompleteQueryResponse.CompletionResult]):
Results of the matching job/company
candidates.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
class CompletionResult(proto.Message):
r"""Resource that represents completion results.
-
Attributes:
suggestion (str):
The suggestion for the query.
- type_ (~.completion_service.CompleteQueryRequest.CompletionType):
+ type_ (google.cloud.talent_v4.types.CompleteQueryRequest.CompletionType):
The completion topic.
image_uri (str):
The URI of the company image for
[COMPANY_NAME][google.cloud.talent.v4.CompleteQueryRequest.CompletionType.COMPANY_NAME].
"""
- suggestion = proto.Field(proto.STRING, number=1)
-
+ suggestion = proto.Field(proto.STRING, number=1,)
type_ = proto.Field(
proto.ENUM, number=2, enum="CompleteQueryRequest.CompletionType",
)
-
- image_uri = proto.Field(proto.STRING, number=3)
+ image_uri = proto.Field(proto.STRING, number=3,)
completion_results = proto.RepeatedField(
proto.MESSAGE, number=1, message=CompletionResult,
)
-
metadata = proto.Field(proto.MESSAGE, number=2, message=common.ResponseMetadata,)
diff --git a/google/cloud/talent_v4/types/event.py b/google/cloud/talent_v4/types/event.py
index 8ecb3a87..ec298642 100644
--- a/google/cloud/talent_v4/types/event.py
+++ b/google/cloud/talent_v4/types/event.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,11 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -44,9 +41,9 @@ class ClientEvent(proto.Message):
event_id (str):
Required. A unique identifier, generated by
the client application.
- create_time (~.timestamp.Timestamp):
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
Required. The timestamp of the event.
- job_event (~.event.JobEvent):
+ job_event (google.cloud.talent_v4.types.JobEvent):
An event issued when a job seeker interacts
with the application that implements Cloud
Talent Solution.
@@ -56,15 +53,11 @@ class ClientEvent(proto.Message):
job was bookmarked.
"""
- request_id = proto.Field(proto.STRING, number=1)
-
- event_id = proto.Field(proto.STRING, number=2)
-
- create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,)
-
+ request_id = proto.Field(proto.STRING, number=1,)
+ event_id = proto.Field(proto.STRING, number=2,)
+ create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,)
job_event = proto.Field(proto.MESSAGE, number=5, oneof="event", message="JobEvent",)
-
- event_notes = proto.Field(proto.STRING, number=9)
+ event_notes = proto.Field(proto.STRING, number=9,)
class JobEvent(proto.Message):
@@ -72,7 +65,7 @@ class JobEvent(proto.Message):
application that implements Cloud Talent Solution.
Attributes:
- type_ (~.event.JobEvent.JobEventType):
+ type_ (google.cloud.talent_v4.types.JobEvent.JobEventType):
Required. The type of the event (see
[JobEventType][google.cloud.talent.v4.JobEvent.JobEventType]).
jobs (Sequence[str]):
@@ -111,8 +104,7 @@ class JobEventType(proto.Enum):
INTERVIEW_GRANTED = 15
type_ = proto.Field(proto.ENUM, number=1, enum=JobEventType,)
-
- jobs = proto.RepeatedField(proto.STRING, number=2)
+ jobs = proto.RepeatedField(proto.STRING, number=2,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4/types/event_service.py b/google/cloud/talent_v4/types/event_service.py
index 264d2f2d..1dea29f7 100644
--- a/google/cloud/talent_v4/types/event_service.py
+++ b/google/cloud/talent_v4/types/event_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,10 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import event
@@ -28,7 +25,6 @@
class CreateClientEventRequest(proto.Message):
r"""The report event request.
-
Attributes:
parent (str):
Required. Resource name of the tenant under which the event
@@ -36,14 +32,13 @@ class CreateClientEventRequest(proto.Message):
The format is "projects/{project_id}/tenants/{tenant_id}",
for example, "projects/foo/tenants/bar".
- client_event (~.event.ClientEvent):
+ client_event (google.cloud.talent_v4.types.ClientEvent):
Required. Events issued when end user
interacts with customer's application that uses
Cloud Talent Solution.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
client_event = proto.Field(proto.MESSAGE, number=2, message=event.ClientEvent,)
diff --git a/google/cloud/talent_v4/types/filters.py b/google/cloud/talent_v4/types/filters.py
index 62a8aa57..1e046b5f 100644
--- a/google/cloud/talent_v4/types/filters.py
+++ b/google/cloud/talent_v4/types/filters.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import common
-from google.protobuf import duration_pb2 as duration # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import timeofday_pb2 as timeofday # type: ignore
+from google.protobuf import duration_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import timeofday_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -32,7 +29,6 @@
class JobQuery(proto.Message):
r"""The query required to perform a search query.
-
Attributes:
query (str):
The query string that matches against the job
@@ -65,7 +61,7 @@ class JobQuery(proto.Message):
For example, "projects/foo/tenants/bar/companies/baz".
At most 20 company filters are allowed.
- location_filters (Sequence[~.filters.LocationFilter]):
+ location_filters (Sequence[google.cloud.talent_v4.types.LocationFilter]):
The location filter specifies geo-regions containing the
jobs to search against. See
[LocationFilter][google.cloud.talent.v4.LocationFilter] for
@@ -83,7 +79,7 @@ class JobQuery(proto.Message):
locations.
At most 5 location filters are allowed.
- job_categories (Sequence[~.common.JobCategory]):
+ job_categories (Sequence[google.cloud.talent_v4.types.JobCategory]):
The category filter specifies the categories of jobs to
search against. See
[JobCategory][google.cloud.talent.v4.JobCategory] for more
@@ -94,7 +90,7 @@ class JobQuery(proto.Message):
If multiple values are specified, jobs from any of the
specified categories are searched against.
- commute_filter (~.filters.CommuteFilter):
+ commute_filter (google.cloud.talent_v4.types.CommuteFilter):
Allows filtering jobs by commute time with different travel
methods (for example, driving or public transit).
@@ -118,7 +114,7 @@ class JobQuery(proto.Message):
companies.
At most 20 company display name filters are allowed.
- compensation_filter (~.filters.CompensationFilter):
+ compensation_filter (google.cloud.talent_v4.types.CompensationFilter):
This search filter is applied only to
[Job.compensation_info][google.cloud.talent.v4.Job.compensation_info].
For example, if the filter is specified as "Hourly job with
@@ -157,7 +153,7 @@ class JobQuery(proto.Message):
misspelled query, for example, "enginee" is
corrected to "engineer".
Defaults to false: a spell check is performed.
- employment_types (Sequence[~.common.EmploymentType]):
+ employment_types (Sequence[google.cloud.talent_v4.types.EmploymentType]):
The employment type filter specifies the employment type of
jobs to search against, such as
[EmploymentType.FULL_TIME][google.cloud.talent.v4.EmploymentType.FULL_TIME].
@@ -180,7 +176,7 @@ class JobQuery(proto.Message):
Languages `__.
At most 10 language code filters are allowed.
- publish_time_range (~.common.TimestampRange):
+ publish_time_range (google.cloud.talent_v4.types.TimestampRange):
Jobs published within a range specified by
this filter are searched against.
excluded_jobs (Sequence[str]):
@@ -189,46 +185,32 @@ class JobQuery(proto.Message):
At most 400 excluded job names are allowed.
"""
- query = proto.Field(proto.STRING, number=1)
-
- query_language_code = proto.Field(proto.STRING, number=14)
-
- companies = proto.RepeatedField(proto.STRING, number=2)
-
+ query = proto.Field(proto.STRING, number=1,)
+ query_language_code = proto.Field(proto.STRING, number=14,)
+ companies = proto.RepeatedField(proto.STRING, number=2,)
location_filters = proto.RepeatedField(
proto.MESSAGE, number=3, message="LocationFilter",
)
-
job_categories = proto.RepeatedField(proto.ENUM, number=4, enum=common.JobCategory,)
-
commute_filter = proto.Field(proto.MESSAGE, number=5, message="CommuteFilter",)
-
- company_display_names = proto.RepeatedField(proto.STRING, number=6)
-
+ company_display_names = proto.RepeatedField(proto.STRING, number=6,)
compensation_filter = proto.Field(
proto.MESSAGE, number=7, message="CompensationFilter",
)
-
- custom_attribute_filter = proto.Field(proto.STRING, number=8)
-
- disable_spell_check = proto.Field(proto.BOOL, number=9)
-
+ custom_attribute_filter = proto.Field(proto.STRING, number=8,)
+ disable_spell_check = proto.Field(proto.BOOL, number=9,)
employment_types = proto.RepeatedField(
proto.ENUM, number=10, enum=common.EmploymentType,
)
-
- language_codes = proto.RepeatedField(proto.STRING, number=11)
-
+ language_codes = proto.RepeatedField(proto.STRING, number=11,)
publish_time_range = proto.Field(
proto.MESSAGE, number=12, message=common.TimestampRange,
)
-
- excluded_jobs = proto.RepeatedField(proto.STRING, number=13)
+ excluded_jobs = proto.RepeatedField(proto.STRING, number=13,)
class LocationFilter(proto.Message):
r"""Geographic region of the search.
-
Attributes:
address (str):
The address name, such as "Mountain View" or
@@ -246,7 +228,7 @@ class LocationFilter(proto.Message):
See
https://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
for details. Example: "CH" for Switzerland.
- lat_lng (~.latlng.LatLng):
+ lat_lng (google.type.latlng_pb2.LatLng):
The latitude and longitude of the geographic center to
search from. This field is ignored if ``address`` is
provided.
@@ -255,7 +237,7 @@ class LocationFilter(proto.Message):
searched for is identified as a city or smaller. This field
is ignored if the location being searched for is a state or
larger.
- telecommute_preference (~.filters.LocationFilter.TelecommutePreference):
+ telecommute_preference (google.cloud.talent_v4.types.LocationFilter.TelecommutePreference):
Allows the client to return jobs without a set location,
specifically, telecommuting jobs (telecommuting is
considered by the service as a special location.
@@ -287,14 +269,10 @@ class TelecommutePreference(proto.Enum):
TELECOMMUTE_EXCLUDED = 1
TELECOMMUTE_ALLOWED = 2
- address = proto.Field(proto.STRING, number=1)
-
- region_code = proto.Field(proto.STRING, number=2)
-
- lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng.LatLng,)
-
- distance_in_miles = proto.Field(proto.DOUBLE, number=4)
-
+ address = proto.Field(proto.STRING, number=1,)
+ region_code = proto.Field(proto.STRING, number=2,)
+ lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng_pb2.LatLng,)
+ distance_in_miles = proto.Field(proto.DOUBLE, number=4,)
telecommute_preference = proto.Field(
proto.ENUM, number=5, enum=TelecommutePreference,
)
@@ -302,14 +280,13 @@ class TelecommutePreference(proto.Enum):
class CompensationFilter(proto.Message):
r"""Filter on job compensation type and amount.
-
Attributes:
- type_ (~.filters.CompensationFilter.FilterType):
+ type_ (google.cloud.talent_v4.types.CompensationFilter.FilterType):
Required. Type of filter.
- units (Sequence[~.common.CompensationInfo.CompensationUnit]):
+ units (Sequence[google.cloud.talent_v4.types.CompensationInfo.CompensationUnit]):
Required. Specify desired ``base compensation entry's``
[CompensationInfo.CompensationUnit][google.cloud.talent.v4.CompensationInfo.CompensationUnit].
- range_ (~.common.CompensationInfo.CompensationRange):
+ range_ (google.cloud.talent_v4.types.CompensationInfo.CompensationRange):
Compensation range.
include_jobs_with_unspecified_compensation_range (bool):
If set to true, jobs with unspecified
@@ -325,29 +302,27 @@ class FilterType(proto.Enum):
ANNUALIZED_TOTAL_AMOUNT = 4
type_ = proto.Field(proto.ENUM, number=1, enum=FilterType,)
-
units = proto.RepeatedField(
proto.ENUM, number=2, enum=common.CompensationInfo.CompensationUnit,
)
-
range_ = proto.Field(
proto.MESSAGE, number=3, message=common.CompensationInfo.CompensationRange,
)
-
- include_jobs_with_unspecified_compensation_range = proto.Field(proto.BOOL, number=4)
+ include_jobs_with_unspecified_compensation_range = proto.Field(
+ proto.BOOL, number=4,
+ )
class CommuteFilter(proto.Message):
r"""Parameters needed for commute search.
-
Attributes:
- commute_method (~.common.CommuteMethod):
+ commute_method (google.cloud.talent_v4.types.CommuteMethod):
Required. The method of transportation to
calculate the commute time for.
- start_coordinates (~.latlng.LatLng):
+ start_coordinates (google.type.latlng_pb2.LatLng):
Required. The latitude and longitude of the
location to calculate the commute time from.
- travel_duration (~.duration.Duration):
+ travel_duration (google.protobuf.duration_pb2.Duration):
Required. The maximum travel time in seconds. The maximum
allowed value is ``3600s`` (one hour). Format is ``123s``.
allow_imprecise_addresses (bool):
@@ -357,10 +332,10 @@ class CommuteFilter(proto.Message):
used. If this field is set to ``false`` or isn't specified,
only jobs that include street level addresses will be
returned by commute search.
- road_traffic (~.filters.CommuteFilter.RoadTraffic):
+ road_traffic (google.cloud.talent_v4.types.CommuteFilter.RoadTraffic):
Specifies the traffic density to use when
calculating commute time.
- departure_time (~.timeofday.TimeOfDay):
+ departure_time (google.type.timeofday_pb2.TimeOfDay):
The departure time used to calculate traffic impact,
represented as
[google.type.TimeOfDay][google.type.TimeOfDay] in local time
@@ -377,19 +352,19 @@ class RoadTraffic(proto.Enum):
BUSY_HOUR = 2
commute_method = proto.Field(proto.ENUM, number=1, enum=common.CommuteMethod,)
-
- start_coordinates = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,)
-
- travel_duration = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,)
-
- allow_imprecise_addresses = proto.Field(proto.BOOL, number=4)
-
+ start_coordinates = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,)
+ travel_duration = proto.Field(
+ proto.MESSAGE, number=3, message=duration_pb2.Duration,
+ )
+ allow_imprecise_addresses = proto.Field(proto.BOOL, number=4,)
road_traffic = proto.Field(
proto.ENUM, number=5, oneof="traffic_option", enum=RoadTraffic,
)
-
departure_time = proto.Field(
- proto.MESSAGE, number=6, oneof="traffic_option", message=timeofday.TimeOfDay,
+ proto.MESSAGE,
+ number=6,
+ oneof="traffic_option",
+ message=timeofday_pb2.TimeOfDay,
)
diff --git a/google/cloud/talent_v4/types/histogram.py b/google/cloud/talent_v4/types/histogram.py
index ac6443df..ce7d8e6b 100644
--- a/google/cloud/talent_v4/types/histogram.py
+++ b/google/cloud/talent_v4/types/histogram.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
@@ -26,7 +24,6 @@
class HistogramQuery(proto.Message):
r"""The histogram request.
-
Attributes:
histogram_query (str):
An expression specifies a histogram request against matching
@@ -37,7 +34,7 @@ class HistogramQuery(proto.Message):
for details about syntax.
"""
- histogram_query = proto.Field(proto.STRING, number=1)
+ histogram_query = proto.Field(proto.STRING, number=1,)
class HistogramQueryResult(proto.Message):
@@ -48,7 +45,7 @@ class HistogramQueryResult(proto.Message):
Attributes:
histogram_query (str):
Requested histogram expression.
- histogram (Sequence[~.gct_histogram.HistogramQueryResult.HistogramEntry]):
+ histogram (Sequence[google.cloud.talent_v4.types.HistogramQueryResult.HistogramEntry]):
A map from the values of the facet associated with distinct
values to the number of matching entries with corresponding
value.
@@ -64,9 +61,8 @@ class HistogramQueryResult(proto.Message):
``0-MAX``.
"""
- histogram_query = proto.Field(proto.STRING, number=1)
-
- histogram = proto.MapField(proto.STRING, proto.INT64, number=2)
+ histogram_query = proto.Field(proto.STRING, number=1,)
+ histogram = proto.MapField(proto.STRING, proto.INT64, number=2,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4/types/job.py b/google/cloud/talent_v4/types/job.py
index f1320f94..2acf9b72 100644
--- a/google/cloud/talent_v4/types/job.py
+++ b/google/cloud/talent_v4/types/job.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,12 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import common
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(package="google.cloud.talent.v4", manifest={"Job",},)
@@ -111,15 +108,15 @@ class Job(proto.Message):
experience.
The maximum number of allowed characters is 500.
- application_info (~.job.Job.ApplicationInfo):
+ application_info (google.cloud.talent_v4.types.Job.ApplicationInfo):
Job application information.
- job_benefits (Sequence[~.common.JobBenefit]):
+ job_benefits (Sequence[google.cloud.talent_v4.types.JobBenefit]):
The benefits included with the job.
- compensation_info (~.common.CompensationInfo):
+ compensation_info (google.cloud.talent_v4.types.CompensationInfo):
Job compensation information (a.k.a. "pay
rate") i.e., the compensation that will paid to
the employee.
- custom_attributes (Sequence[~.job.Job.CustomAttributesEntry]):
+ custom_attributes (Sequence[google.cloud.talent_v4.types.Job.CustomAttributesEntry]):
A map of fields to hold both filterable and non-filterable
custom job attributes that are not covered by the provided
structured fields.
@@ -134,7 +131,7 @@ class Job(proto.Message):
than 255 characters. For unfilterable ``string_values``, the
maximum total size of ``string_values`` across all keys is
50KB.
- degree_types (Sequence[~.common.DegreeType]):
+ degree_types (Sequence[google.cloud.talent_v4.types.DegreeType]):
The desired education degrees for the job,
such as Bachelors, Masters.
department (str):
@@ -142,7 +139,7 @@ class Job(proto.Message):
company with the open position.
The maximum number of allowed characters is 255.
- employment_types (Sequence[~.common.EmploymentType]):
+ employment_types (Sequence[google.cloud.talent_v4.types.EmploymentType]):
The employment type(s) of a job, for example, [full
time][google.cloud.talent.v4.EmploymentType.FULL_TIME] or
[part
@@ -167,7 +164,7 @@ class Job(proto.Message):
present, detected language code based on
[Job.description][google.cloud.talent.v4.Job.description] is
assigned, otherwise defaults to 'en_US'.
- job_level (~.common.JobLevel):
+ job_level (google.cloud.talent_v4.types.JobLevel):
The experience level associated with the job,
such as "Entry Level".
promotion_value (int):
@@ -200,7 +197,7 @@ class Job(proto.Message):
markup tags.
The maximum number of allowed characters is 10,000.
- posting_region (~.common.PostingRegion):
+ posting_region (google.cloud.talent_v4.types.PostingRegion):
The job
[PostingRegion][google.cloud.talent.v4.PostingRegion] (for
example, state, country) throughout which the job is
@@ -215,7 +212,7 @@ class Job(proto.Message):
setting job
[Job.addresses][google.cloud.talent.v4.Job.addresses] to the
same location level as this field is strongly recommended.
- visibility (~.common.Visibility):
+ visibility (google.cloud.talent_v4.types.Visibility):
Deprecated. The job is only visible to the owner.
The visibility of the job.
@@ -223,21 +220,21 @@ class Job(proto.Message):
Defaults to
[Visibility.ACCOUNT_ONLY][google.cloud.talent.v4.Visibility.ACCOUNT_ONLY]
if not specified.
- job_start_time (~.timestamp.Timestamp):
+ job_start_time (google.protobuf.timestamp_pb2.Timestamp):
The start timestamp of the job in UTC time
zone. Typically this field is used for
contracting engagements. Invalid timestamps are
ignored.
- job_end_time (~.timestamp.Timestamp):
+ job_end_time (google.protobuf.timestamp_pb2.Timestamp):
The end timestamp of the job. Typically this
field is used for contracting engagements.
Invalid timestamps are ignored.
- posting_publish_time (~.timestamp.Timestamp):
+ posting_publish_time (google.protobuf.timestamp_pb2.Timestamp):
The timestamp this job posting was most
recently published. The default value is the
time the request arrives at the server. Invalid
timestamps are ignored.
- posting_expire_time (~.timestamp.Timestamp):
+ posting_expire_time (google.protobuf.timestamp_pb2.Timestamp):
Strongly recommended for the best service experience.
The expiration timestamp of the job. After this timestamp,
@@ -295,25 +292,24 @@ class Job(proto.Message):
the masks are empty meaning that every field is updated, the
job posting expires after 30 days from the job's last update
time. Otherwise the expiration date isn't updated.
- posting_create_time (~.timestamp.Timestamp):
+ posting_create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The timestamp when this job
posting was created.
- posting_update_time (~.timestamp.Timestamp):
+ posting_update_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The timestamp when this job
posting was last updated.
company_display_name (str):
Output only. Display name of the company
listing the job.
- derived_info (~.job.Job.DerivedInfo):
+ derived_info (google.cloud.talent_v4.types.Job.DerivedInfo):
Output only. Derived details about the job
posting.
- processing_options (~.job.Job.ProcessingOptions):
+ processing_options (google.cloud.talent_v4.types.Job.ProcessingOptions):
Options for job processing.
"""
class ApplicationInfo(proto.Message):
r"""Application related details of a job posting.
-
Attributes:
emails (Sequence[str]):
Use this field to specify email address(es)
@@ -337,17 +333,14 @@ class ApplicationInfo(proto.Message):
each entry is 2,000.
"""
- emails = proto.RepeatedField(proto.STRING, number=1)
-
- instruction = proto.Field(proto.STRING, number=2)
-
- uris = proto.RepeatedField(proto.STRING, number=3)
+ emails = proto.RepeatedField(proto.STRING, number=1,)
+ instruction = proto.Field(proto.STRING, number=2,)
+ uris = proto.RepeatedField(proto.STRING, number=3,)
class DerivedInfo(proto.Message):
r"""Derived details about the job posting.
-
Attributes:
- locations (Sequence[~.common.Location]):
+ locations (Sequence[google.cloud.talent_v4.types.Location]):
Structured locations of the job, resolved from
[Job.addresses][google.cloud.talent.v4.Job.addresses].
@@ -355,7 +348,7 @@ class DerivedInfo(proto.Message):
are exactly matched to
[Job.addresses][google.cloud.talent.v4.Job.addresses] in the
same order.
- job_categories (Sequence[~.common.JobCategory]):
+ job_categories (Sequence[google.cloud.talent_v4.types.JobCategory]):
Job categories derived from
[Job.title][google.cloud.talent.v4.Job.title] and
[Job.description][google.cloud.talent.v4.Job.description].
@@ -364,19 +357,17 @@ class DerivedInfo(proto.Message):
locations = proto.RepeatedField(
proto.MESSAGE, number=1, message=common.Location,
)
-
job_categories = proto.RepeatedField(
proto.ENUM, number=3, enum=common.JobCategory,
)
class ProcessingOptions(proto.Message):
r"""Options for job processing.
-
Attributes:
disable_street_address_resolution (bool):
If set to ``true``, the service does not attempt to resolve
a more precise address for the job.
- html_sanitization (~.common.HtmlSanitization):
+ html_sanitization (google.cloud.talent_v4.types.HtmlSanitization):
Option for job HTML content sanitization. Applied fields
are:
@@ -393,84 +384,58 @@ class ProcessingOptions(proto.Message):
[HtmlSanitization.SIMPLE_FORMATTING_ONLY][google.cloud.talent.v4.HtmlSanitization.SIMPLE_FORMATTING_ONLY].
"""
- disable_street_address_resolution = proto.Field(proto.BOOL, number=1)
-
+ disable_street_address_resolution = proto.Field(proto.BOOL, number=1,)
html_sanitization = proto.Field(
proto.ENUM, number=2, enum=common.HtmlSanitization,
)
- name = proto.Field(proto.STRING, number=1)
-
- company = proto.Field(proto.STRING, number=2)
-
- requisition_id = proto.Field(proto.STRING, number=3)
-
- title = proto.Field(proto.STRING, number=4)
-
- description = proto.Field(proto.STRING, number=5)
-
- addresses = proto.RepeatedField(proto.STRING, number=6)
-
+ name = proto.Field(proto.STRING, number=1,)
+ company = proto.Field(proto.STRING, number=2,)
+ requisition_id = proto.Field(proto.STRING, number=3,)
+ title = proto.Field(proto.STRING, number=4,)
+ description = proto.Field(proto.STRING, number=5,)
+ addresses = proto.RepeatedField(proto.STRING, number=6,)
application_info = proto.Field(proto.MESSAGE, number=7, message=ApplicationInfo,)
-
job_benefits = proto.RepeatedField(proto.ENUM, number=8, enum=common.JobBenefit,)
-
compensation_info = proto.Field(
proto.MESSAGE, number=9, message=common.CompensationInfo,
)
-
custom_attributes = proto.MapField(
proto.STRING, proto.MESSAGE, number=10, message=common.CustomAttribute,
)
-
degree_types = proto.RepeatedField(proto.ENUM, number=11, enum=common.DegreeType,)
-
- department = proto.Field(proto.STRING, number=12)
-
+ department = proto.Field(proto.STRING, number=12,)
employment_types = proto.RepeatedField(
proto.ENUM, number=13, enum=common.EmploymentType,
)
-
- incentives = proto.Field(proto.STRING, number=14)
-
- language_code = proto.Field(proto.STRING, number=15)
-
+ incentives = proto.Field(proto.STRING, number=14,)
+ language_code = proto.Field(proto.STRING, number=15,)
job_level = proto.Field(proto.ENUM, number=16, enum=common.JobLevel,)
-
- promotion_value = proto.Field(proto.INT32, number=17)
-
- qualifications = proto.Field(proto.STRING, number=18)
-
- responsibilities = proto.Field(proto.STRING, number=19)
-
+ promotion_value = proto.Field(proto.INT32, number=17,)
+ qualifications = proto.Field(proto.STRING, number=18,)
+ responsibilities = proto.Field(proto.STRING, number=19,)
posting_region = proto.Field(proto.ENUM, number=20, enum=common.PostingRegion,)
-
visibility = proto.Field(proto.ENUM, number=21, enum=common.Visibility,)
-
- job_start_time = proto.Field(proto.MESSAGE, number=22, message=timestamp.Timestamp,)
-
- job_end_time = proto.Field(proto.MESSAGE, number=23, message=timestamp.Timestamp,)
-
+ job_start_time = proto.Field(
+ proto.MESSAGE, number=22, message=timestamp_pb2.Timestamp,
+ )
+ job_end_time = proto.Field(
+ proto.MESSAGE, number=23, message=timestamp_pb2.Timestamp,
+ )
posting_publish_time = proto.Field(
- proto.MESSAGE, number=24, message=timestamp.Timestamp,
+ proto.MESSAGE, number=24, message=timestamp_pb2.Timestamp,
)
-
posting_expire_time = proto.Field(
- proto.MESSAGE, number=25, message=timestamp.Timestamp,
+ proto.MESSAGE, number=25, message=timestamp_pb2.Timestamp,
)
-
posting_create_time = proto.Field(
- proto.MESSAGE, number=26, message=timestamp.Timestamp,
+ proto.MESSAGE, number=26, message=timestamp_pb2.Timestamp,
)
-
posting_update_time = proto.Field(
- proto.MESSAGE, number=27, message=timestamp.Timestamp,
+ proto.MESSAGE, number=27, message=timestamp_pb2.Timestamp,
)
-
- company_display_name = proto.Field(proto.STRING, number=28)
-
+ company_display_name = proto.Field(proto.STRING, number=28,)
derived_info = proto.Field(proto.MESSAGE, number=29, message=DerivedInfo,)
-
processing_options = proto.Field(
proto.MESSAGE, number=30, message=ProcessingOptions,
)
diff --git a/google/cloud/talent_v4/types/job_service.py b/google/cloud/talent_v4/types/job_service.py
index 4b53ed10..90edb34d 100644
--- a/google/cloud/talent_v4/types/job_service.py
+++ b/google/cloud/talent_v4/types/job_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,17 +13,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import filters
from google.cloud.talent_v4.types import histogram
from google.cloud.talent_v4.types import job as gct_job
-from google.protobuf import duration_pb2 as duration # type: ignore
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.rpc import status_pb2 as gr_status # type: ignore
+from google.protobuf import duration_pb2 # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.rpc import status_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -66,7 +63,6 @@ class JobView(proto.Enum):
class CreateJobRequest(proto.Message):
r"""Create job request.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -74,18 +70,16 @@ class CreateJobRequest(proto.Message):
The format is "projects/{project_id}/tenants/{tenant_id}".
For example, "projects/foo/tenants/bar".
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4.types.Job):
Required. The Job to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
job = proto.Field(proto.MESSAGE, number=2, message=gct_job.Job,)
class GetJobRequest(proto.Message):
r"""Get job request.
-
Attributes:
name (str):
Required. The resource name of the job to retrieve.
@@ -95,16 +89,15 @@ class GetJobRequest(proto.Message):
For example, "projects/foo/tenants/bar/jobs/baz".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateJobRequest(proto.Message):
r"""Update job request.
-
Attributes:
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4.types.Job):
Required. The Job to be updated.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -119,13 +112,13 @@ class UpdateJobRequest(proto.Message):
"""
job = proto.Field(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteJobRequest(proto.Message):
r"""Delete job request.
-
Attributes:
name (str):
Required. The resource name of the job to be deleted.
@@ -135,12 +128,11 @@ class DeleteJobRequest(proto.Message):
For example, "projects/foo/tenants/bar/jobs/baz".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class ListJobsRequest(proto.Message):
r"""List jobs request.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -182,35 +174,30 @@ class ListJobsRequest(proto.Message):
maximum allowed page size is 100.
Default is 100 if empty or a number < 1 is specified.
- job_view (~.job_service.JobView):
+ job_view (google.cloud.talent_v4.types.JobView):
The desired job attributes returned for jobs in the search
response. Defaults to
[JobView.JOB_VIEW_FULL][google.cloud.talent.v4.JobView.JOB_VIEW_FULL]
if no value is specified.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- filter = proto.Field(proto.STRING, number=2)
-
- page_token = proto.Field(proto.STRING, number=3)
-
- page_size = proto.Field(proto.INT32, number=4)
-
+ parent = proto.Field(proto.STRING, number=1,)
+ filter = proto.Field(proto.STRING, number=2,)
+ page_token = proto.Field(proto.STRING, number=3,)
+ page_size = proto.Field(proto.INT32, number=4,)
job_view = proto.Field(proto.ENUM, number=5, enum="JobView",)
class ListJobsResponse(proto.Message):
r"""List jobs response.
-
Attributes:
- jobs (Sequence[~.gct_job.Job]):
+ jobs (Sequence[google.cloud.talent_v4.types.Job]):
The Jobs for a given company.
The maximum number of items returned is based on
the limit field provided in the request.
next_page_token (str):
A token to retrieve the next page of results.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
@@ -220,32 +207,29 @@ def raw_page(self):
return self
jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- next_page_token = proto.Field(proto.STRING, number=2)
-
+ next_page_token = proto.Field(proto.STRING, number=2,)
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
class SearchJobsRequest(proto.Message):
r"""The Request body of the ``SearchJobs`` call.
-
Attributes:
parent (str):
Required. The resource name of the tenant to search within.
The format is "projects/{project_id}/tenants/{tenant_id}".
For example, "projects/foo/tenants/bar".
- search_mode (~.job_service.SearchJobsRequest.SearchMode):
+ search_mode (google.cloud.talent_v4.types.SearchJobsRequest.SearchMode):
Mode of a search.
Defaults to
[SearchMode.JOB_SEARCH][google.cloud.talent.v4.SearchJobsRequest.SearchMode.JOB_SEARCH].
- request_metadata (~.common.RequestMetadata):
+ request_metadata (google.cloud.talent_v4.types.RequestMetadata):
Required. The meta information collected about the job
searcher, used to improve the search quality of the service.
The identifiers (such as ``user_id``) are provided by users,
and must be unique and consistent.
- job_query (~.filters.JobQuery):
+ job_query (google.cloud.talent_v4.types.JobQuery):
Query used to search against jobs, such as
keyword, location filters, etc.
enable_broadening (bool):
@@ -255,7 +239,7 @@ class SearchJobsRequest(proto.Message):
results list.
Defaults to false.
- histogram_queries (Sequence[~.histogram.HistogramQuery]):
+ histogram_queries (Sequence[google.cloud.talent_v4.types.HistogramQuery]):
An expression specifies a histogram request against matching
jobs.
@@ -368,7 +352,7 @@ class SearchJobsRequest(proto.Message):
- ``count(base_compensation, [bucket(1000, 10000), bucket(10000, 100000), bucket(100000, MAX)])``
- ``count(string_custom_attribute["some-string-custom-attribute"])``
- ``count(numeric_custom_attribute["some-numeric-custom-attribute"], [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative"])``
- job_view (~.job_service.JobView):
+ job_view (google.cloud.talent_v4.types.JobView):
The desired job attributes returned for jobs in the search
response. Defaults to
[JobView.JOB_VIEW_SMALL][google.cloud.talent.v4.JobView.JOB_VIEW_SMALL]
@@ -458,7 +442,7 @@ class SearchJobsRequest(proto.Message):
(37.4 feet). Diversification strategy is still applied
unless explicitly disabled in
[diversification_level][google.cloud.talent.v4.SearchJobsRequest.diversification_level].
- diversification_level (~.job_service.SearchJobsRequest.DiversificationLevel):
+ diversification_level (google.cloud.talent_v4.types.SearchJobsRequest.DiversificationLevel):
Controls whether highly similar jobs are returned next to
each other in the search results. Jobs are identified as
highly similar based on their titles, job categories, and
@@ -470,7 +454,7 @@ class SearchJobsRequest(proto.Message):
Defaults to
[DiversificationLevel.SIMPLE][google.cloud.talent.v4.SearchJobsRequest.DiversificationLevel.SIMPLE]
if no value is specified.
- custom_ranking_info (~.job_service.SearchJobsRequest.CustomRankingInfo):
+ custom_ranking_info (google.cloud.talent_v4.types.SearchJobsRequest.CustomRankingInfo):
Controls over how job documents get ranked on
top of existing relevance score (determined by
API algorithm).
@@ -528,7 +512,7 @@ class CustomRankingInfo(proto.Message):
[SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
Attributes:
- importance_level (~.job_service.SearchJobsRequest.CustomRankingInfo.ImportanceLevel):
+ importance_level (google.cloud.talent_v4.types.SearchJobsRequest.CustomRankingInfo.ImportanceLevel):
Required. Controls over how important the score of
[CustomRankingInfo.ranking_expression][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.ranking_expression]
gets applied to job's final ranking position.
@@ -579,61 +563,46 @@ class ImportanceLevel(proto.Enum):
number=1,
enum="SearchJobsRequest.CustomRankingInfo.ImportanceLevel",
)
+ ranking_expression = proto.Field(proto.STRING, number=2,)
- ranking_expression = proto.Field(proto.STRING, number=2)
-
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
search_mode = proto.Field(proto.ENUM, number=2, enum=SearchMode,)
-
request_metadata = proto.Field(
proto.MESSAGE, number=3, message=common.RequestMetadata,
)
-
job_query = proto.Field(proto.MESSAGE, number=4, message=filters.JobQuery,)
-
- enable_broadening = proto.Field(proto.BOOL, number=5)
-
+ enable_broadening = proto.Field(proto.BOOL, number=5,)
histogram_queries = proto.RepeatedField(
proto.MESSAGE, number=7, message=histogram.HistogramQuery,
)
-
job_view = proto.Field(proto.ENUM, number=8, enum="JobView",)
-
- offset = proto.Field(proto.INT32, number=9)
-
- max_page_size = proto.Field(proto.INT32, number=10)
-
- page_token = proto.Field(proto.STRING, number=11)
-
- order_by = proto.Field(proto.STRING, number=12)
-
+ offset = proto.Field(proto.INT32, number=9,)
+ max_page_size = proto.Field(proto.INT32, number=10,)
+ page_token = proto.Field(proto.STRING, number=11,)
+ order_by = proto.Field(proto.STRING, number=12,)
diversification_level = proto.Field(
proto.ENUM, number=13, enum=DiversificationLevel,
)
-
custom_ranking_info = proto.Field(
proto.MESSAGE, number=14, message=CustomRankingInfo,
)
-
- disable_keyword_match = proto.Field(proto.BOOL, number=16)
+ disable_keyword_match = proto.Field(proto.BOOL, number=16,)
class SearchJobsResponse(proto.Message):
r"""Response for SearchJob method.
-
Attributes:
- matching_jobs (Sequence[~.job_service.SearchJobsResponse.MatchingJob]):
+ matching_jobs (Sequence[google.cloud.talent_v4.types.SearchJobsResponse.MatchingJob]):
The Job entities that match the specified
[SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
- histogram_query_results (Sequence[~.histogram.HistogramQueryResult]):
+ histogram_query_results (Sequence[google.cloud.talent_v4.types.HistogramQueryResult]):
The histogram results that match with specified
[SearchJobsRequest.histogram_queries][google.cloud.talent.v4.SearchJobsRequest.histogram_queries].
next_page_token (str):
The token that specifies the starting
position of the next page of results. This field
is empty if there are no more results.
- location_filters (Sequence[~.common.Location]):
+ location_filters (Sequence[google.cloud.talent_v4.types.Location]):
The location filters that the service applied to the
specified query. If any filters are lat-lng based, the
[Location.location_type][google.cloud.talent.v4.Location.location_type]
@@ -644,7 +613,7 @@ class SearchJobsResponse(proto.Message):
query.
Note: This size is precise only if the total is
less than 100,000.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
broadened_query_jobs_count (int):
@@ -659,7 +628,7 @@ class SearchJobsResponse(proto.Message):
broadening) query. If this field is non-zero,
subsequent requests with offset after this
result set should contain all broadened results.
- spell_correction (~.common.SpellingCorrection):
+ spell_correction (google.cloud.talent_v4.types.SpellingCorrection):
The spell checking result, and correction.
"""
@@ -668,7 +637,7 @@ class MatchingJob(proto.Message):
[SearchJobsResponse][google.cloud.talent.v4.SearchJobsResponse].
Attributes:
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4.types.Job):
Job resource that matches the specified
[SearchJobsRequest][google.cloud.talent.v4.SearchJobsRequest].
job_summary (str):
@@ -687,31 +656,26 @@ class MatchingJob(proto.Message):
keywords, if available. All HTML tags in the original fields
are stripped when returned in this field, and matching query
keywords are enclosed in HTML bold tags.
- commute_info (~.job_service.SearchJobsResponse.CommuteInfo):
+ commute_info (google.cloud.talent_v4.types.SearchJobsResponse.CommuteInfo):
Commute information which is generated based on specified
[CommuteFilter][google.cloud.talent.v4.CommuteFilter].
"""
job = proto.Field(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- job_summary = proto.Field(proto.STRING, number=2)
-
- job_title_snippet = proto.Field(proto.STRING, number=3)
-
- search_text_snippet = proto.Field(proto.STRING, number=4)
-
+ job_summary = proto.Field(proto.STRING, number=2,)
+ job_title_snippet = proto.Field(proto.STRING, number=3,)
+ search_text_snippet = proto.Field(proto.STRING, number=4,)
commute_info = proto.Field(
proto.MESSAGE, number=5, message="SearchJobsResponse.CommuteInfo",
)
class CommuteInfo(proto.Message):
r"""Commute details related to this job.
-
Attributes:
- job_location (~.common.Location):
+ job_location (google.cloud.talent_v4.types.Location):
Location used as the destination in the
commute calculation.
- travel_duration (~.duration.Duration):
+ travel_duration (google.protobuf.duration_pb2.Duration):
The number of seconds required to travel to
the job location from the query location. A
duration of 0 seconds indicates that the job
@@ -720,9 +684,8 @@ class CommuteInfo(proto.Message):
"""
job_location = proto.Field(proto.MESSAGE, number=1, message=common.Location,)
-
travel_duration = proto.Field(
- proto.MESSAGE, number=2, message=duration.Duration,
+ proto.MESSAGE, number=2, message=duration_pb2.Duration,
)
@property
@@ -730,23 +693,16 @@ def raw_page(self):
return self
matching_jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=MatchingJob,)
-
histogram_query_results = proto.RepeatedField(
proto.MESSAGE, number=2, message=histogram.HistogramQueryResult,
)
-
- next_page_token = proto.Field(proto.STRING, number=3)
-
+ next_page_token = proto.Field(proto.STRING, number=3,)
location_filters = proto.RepeatedField(
proto.MESSAGE, number=4, message=common.Location,
)
-
- total_size = proto.Field(proto.INT32, number=6)
-
+ total_size = proto.Field(proto.INT32, number=6,)
metadata = proto.Field(proto.MESSAGE, number=7, message=common.ResponseMetadata,)
-
- broadened_query_jobs_count = proto.Field(proto.INT32, number=8)
-
+ broadened_query_jobs_count = proto.Field(proto.INT32, number=8,)
spell_correction = proto.Field(
proto.MESSAGE, number=9, message=common.SpellingCorrection,
)
@@ -754,7 +710,6 @@ def raw_page(self):
class BatchCreateJobsRequest(proto.Message):
r"""Request to create a batch of jobs.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -762,19 +717,17 @@ class BatchCreateJobsRequest(proto.Message):
The format is "projects/{project_id}/tenants/{tenant_id}".
For example, "projects/foo/tenants/bar".
- jobs (Sequence[~.gct_job.Job]):
+ jobs (Sequence[google.cloud.talent_v4.types.Job]):
Required. The jobs to be created.
A maximum of 200 jobs can be created in a batch.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
jobs = proto.RepeatedField(proto.MESSAGE, number=2, message=gct_job.Job,)
class BatchUpdateJobsRequest(proto.Message):
r"""Request to update a batch of jobs.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -782,10 +735,10 @@ class BatchUpdateJobsRequest(proto.Message):
The format is "projects/{project_id}/tenants/{tenant_id}".
For example, "projects/foo/tenants/bar".
- jobs (Sequence[~.gct_job.Job]):
+ jobs (Sequence[google.cloud.talent_v4.types.Job]):
Required. The jobs to be updated.
A maximum of 200 jobs can be updated in a batch.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience. Be
aware that it will also increase latency when checking the
status of a batch operation.
@@ -809,16 +762,15 @@ class BatchUpdateJobsRequest(proto.Message):
which can yield a very large response.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
jobs = proto.RepeatedField(proto.MESSAGE, number=2, message=gct_job.Job,)
-
- update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask,
+ )
class BatchDeleteJobsRequest(proto.Message):
r"""Request to delete a batch of jobs.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -839,16 +791,14 @@ class BatchDeleteJobsRequest(proto.Message):
A maximum of 200 jobs can be deleted in a batch.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- names = proto.RepeatedField(proto.STRING, number=2)
+ parent = proto.Field(proto.STRING, number=1,)
+ names = proto.RepeatedField(proto.STRING, number=2,)
class JobResult(proto.Message):
r"""Mutation result of a job from a batch operation.
-
Attributes:
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4.types.Job):
Here [Job][google.cloud.talent.v4.Job] only contains basic
information including
[name][google.cloud.talent.v4.Job.name],
@@ -858,15 +808,14 @@ class JobResult(proto.Message):
[requisition_id][google.cloud.talent.v4.Job.requisition_id],
use getJob method to retrieve detailed information of the
created/updated job.
- status (~.gr_status.Status):
+ status (google.rpc.status_pb2.Status):
The status of the job processed. This field is populated if
the processing of the
[job][google.cloud.talent.v4.JobResult.job] fails.
"""
job = proto.Field(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,)
+ status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,)
class BatchCreateJobsResponse(proto.Message):
@@ -877,7 +826,7 @@ class BatchCreateJobsResponse(proto.Message):
in case of success.
Attributes:
- job_results (Sequence[~.job_service.JobResult]):
+ job_results (Sequence[google.cloud.talent_v4.types.JobResult]):
List of job mutation results from a batch
create operation. It can change until operation
status is FINISHED, FAILED or CANCELLED.
@@ -894,7 +843,7 @@ class BatchUpdateJobsResponse(proto.Message):
in case of success.
Attributes:
- job_results (Sequence[~.job_service.JobResult]):
+ job_results (Sequence[google.cloud.talent_v4.types.JobResult]):
List of job mutation results from a batch
update operation. It can change until operation
status is FINISHED, FAILED or CANCELLED.
@@ -911,7 +860,7 @@ class BatchDeleteJobsResponse(proto.Message):
in case of success.
Attributes:
- job_results (Sequence[~.job_service.JobResult]):
+ job_results (Sequence[google.cloud.talent_v4.types.JobResult]):
List of job mutation results from a batch
delete operation. It can change until operation
status is FINISHED, FAILED or CANCELLED.
diff --git a/google/cloud/talent_v4/types/tenant.py b/google/cloud/talent_v4/types/tenant.py
index f28d172f..fc00e67e 100644
--- a/google/cloud/talent_v4/types/tenant.py
+++ b/google/cloud/talent_v4/types/tenant.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
@@ -42,9 +40,8 @@ class Tenant(proto.Message):
The maximum number of allowed characters is 255.
"""
- name = proto.Field(proto.STRING, number=1)
-
- external_id = proto.Field(proto.STRING, number=2)
+ name = proto.Field(proto.STRING, number=1,)
+ external_id = proto.Field(proto.STRING, number=2,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4/types/tenant_service.py b/google/cloud/talent_v4/types/tenant_service.py
index 2f77b0d1..efd0a032 100644
--- a/google/cloud/talent_v4/types/tenant_service.py
+++ b/google/cloud/talent_v4/types/tenant_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,13 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import tenant as gct_tenant
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -38,7 +35,6 @@
class CreateTenantRequest(proto.Message):
r"""The Request of the CreateTenant method.
-
Attributes:
parent (str):
Required. Resource name of the project under which the
@@ -46,18 +42,16 @@ class CreateTenantRequest(proto.Message):
The format is "projects/{project_id}", for example,
"projects/foo".
- tenant (~.gct_tenant.Tenant):
+ tenant (google.cloud.talent_v4.types.Tenant):
Required. The tenant to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
tenant = proto.Field(proto.MESSAGE, number=2, message=gct_tenant.Tenant,)
class GetTenantRequest(proto.Message):
r"""Request for getting a tenant by name.
-
Attributes:
name (str):
Required. The resource name of the tenant to be retrieved.
@@ -66,17 +60,16 @@ class GetTenantRequest(proto.Message):
for example, "projects/foo/tenants/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateTenantRequest(proto.Message):
r"""Request for updating a specified tenant.
-
Attributes:
- tenant (~.gct_tenant.Tenant):
+ tenant (google.cloud.talent_v4.types.Tenant):
Required. The tenant resource to replace the
current resource in the system.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -91,13 +84,13 @@ class UpdateTenantRequest(proto.Message):
"""
tenant = proto.Field(proto.MESSAGE, number=1, message=gct_tenant.Tenant,)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteTenantRequest(proto.Message):
r"""Request to delete a tenant.
-
Attributes:
name (str):
Required. The resource name of the tenant to be deleted.
@@ -106,12 +99,11 @@ class DeleteTenantRequest(proto.Message):
for example, "projects/foo/tenants/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class ListTenantsRequest(proto.Message):
r"""List tenants for which the client has ACL visibility.
-
Attributes:
parent (str):
Required. Resource name of the project under which the
@@ -128,22 +120,19 @@ class ListTenantsRequest(proto.Message):
number is provided.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- page_token = proto.Field(proto.STRING, number=2)
-
- page_size = proto.Field(proto.INT32, number=3)
+ parent = proto.Field(proto.STRING, number=1,)
+ page_token = proto.Field(proto.STRING, number=2,)
+ page_size = proto.Field(proto.INT32, number=3,)
class ListTenantsResponse(proto.Message):
r"""The List tenants response object.
-
Attributes:
- tenants (Sequence[~.gct_tenant.Tenant]):
+ tenants (Sequence[google.cloud.talent_v4.types.Tenant]):
Tenants for the current client.
next_page_token (str):
A token to retrieve the next page of results.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
@@ -153,9 +142,7 @@ def raw_page(self):
return self
tenants = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_tenant.Tenant,)
-
- next_page_token = proto.Field(proto.STRING, number=2)
-
+ next_page_token = proto.Field(proto.STRING, number=2,)
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
diff --git a/google/cloud/talent_v4beta1/__init__.py b/google/cloud/talent_v4beta1/__init__.py
index e486a156..db05b04b 100644
--- a/google/cloud/talent_v4beta1/__init__.py
+++ b/google/cloud/talent_v4beta1/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,12 +15,20 @@
#
from .services.application_service import ApplicationServiceClient
+from .services.application_service import ApplicationServiceAsyncClient
from .services.company_service import CompanyServiceClient
+from .services.company_service import CompanyServiceAsyncClient
from .services.completion import CompletionClient
+from .services.completion import CompletionAsyncClient
from .services.event_service import EventServiceClient
+from .services.event_service import EventServiceAsyncClient
from .services.job_service import JobServiceClient
+from .services.job_service import JobServiceAsyncClient
from .services.profile_service import ProfileServiceClient
+from .services.profile_service import ProfileServiceAsyncClient
from .services.tenant_service import TenantServiceClient
+from .services.tenant_service import TenantServiceAsyncClient
+
from .types.application import Application
from .types.application_service import CreateApplicationRequest
from .types.application_service import DeleteApplicationRequest
@@ -29,32 +36,32 @@
from .types.application_service import ListApplicationsRequest
from .types.application_service import ListApplicationsResponse
from .types.application_service import UpdateApplicationRequest
-from .types.common import AvailabilitySignalType
from .types.common import BatchOperationMetadata
from .types.common import Certification
+from .types.common import CompensationInfo
+from .types.common import CustomAttribute
+from .types.common import DeviceInfo
+from .types.common import Interview
+from .types.common import Location
+from .types.common import Rating
+from .types.common import RequestMetadata
+from .types.common import ResponseMetadata
+from .types.common import Skill
+from .types.common import SpellingCorrection
+from .types.common import TimestampRange
+from .types.common import AvailabilitySignalType
from .types.common import CommuteMethod
from .types.common import CompanySize
-from .types.common import CompensationInfo
from .types.common import ContactInfoUsage
-from .types.common import CustomAttribute
from .types.common import DegreeType
-from .types.common import DeviceInfo
from .types.common import EmploymentType
from .types.common import HtmlSanitization
-from .types.common import Interview
from .types.common import JobBenefit
from .types.common import JobCategory
from .types.common import JobLevel
-from .types.common import Location
from .types.common import Outcome
from .types.common import PostingRegion
-from .types.common import Rating
-from .types.common import RequestMetadata
-from .types.common import ResponseMetadata
-from .types.common import Skill
from .types.common import SkillProficiencyLevel
-from .types.common import SpellingCorrection
-from .types.common import TimestampRange
from .types.common import Visibility
from .types.company import Company
from .types.company_service import CreateCompanyRequest
@@ -96,12 +103,12 @@
from .types.job_service import DeleteJobRequest
from .types.job_service import GetJobRequest
from .types.job_service import JobOperationResult
-from .types.job_service import JobView
from .types.job_service import ListJobsRequest
from .types.job_service import ListJobsResponse
from .types.job_service import SearchJobsRequest
from .types.job_service import SearchJobsResponse
from .types.job_service import UpdateJobRequest
+from .types.job_service import JobView
from .types.profile import Activity
from .types.profile import AdditionalContactInfo
from .types.profile import Address
@@ -111,8 +118,8 @@
from .types.profile import Email
from .types.profile import EmploymentRecord
from .types.profile import Patent
-from .types.profile import PersonName
from .types.profile import PersonalUri
+from .types.profile import PersonName
from .types.profile import Phone
from .types.profile import Profile
from .types.profile import Publication
@@ -134,8 +141,14 @@
from .types.tenant_service import ListTenantsResponse
from .types.tenant_service import UpdateTenantRequest
-
__all__ = (
+ "ApplicationServiceAsyncClient",
+ "CompanyServiceAsyncClient",
+ "CompletionAsyncClient",
+ "EventServiceAsyncClient",
+ "JobServiceAsyncClient",
+ "ProfileServiceAsyncClient",
+ "TenantServiceAsyncClient",
"Activity",
"AdditionalContactInfo",
"Address",
@@ -186,6 +199,7 @@
"EmployerFilter",
"EmploymentRecord",
"EmploymentType",
+ "EventServiceClient",
"GetApplicationRequest",
"GetCompanyRequest",
"GetJobRequest",
@@ -253,5 +267,4 @@
"UpdateTenantRequest",
"Visibility",
"WorkExperienceFilter",
- "EventServiceClient",
)
diff --git a/google/cloud/talent_v4beta1/gapic_metadata.json b/google/cloud/talent_v4beta1/gapic_metadata.json
new file mode 100644
index 00000000..f8bf14c6
--- /dev/null
+++ b/google/cloud/talent_v4beta1/gapic_metadata.json
@@ -0,0 +1,437 @@
+ {
+ "comment": "This file maps proto services/RPCs to the corresponding library clients/methods",
+ "language": "python",
+ "libraryPackage": "google.cloud.talent_v4beta1",
+ "protoPackage": "google.cloud.talent.v4beta1",
+ "schema": "1.0",
+ "services": {
+ "ApplicationService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "ApplicationServiceClient",
+ "rpcs": {
+ "CreateApplication": {
+ "methods": [
+ "create_application"
+ ]
+ },
+ "DeleteApplication": {
+ "methods": [
+ "delete_application"
+ ]
+ },
+ "GetApplication": {
+ "methods": [
+ "get_application"
+ ]
+ },
+ "ListApplications": {
+ "methods": [
+ "list_applications"
+ ]
+ },
+ "UpdateApplication": {
+ "methods": [
+ "update_application"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "ApplicationServiceAsyncClient",
+ "rpcs": {
+ "CreateApplication": {
+ "methods": [
+ "create_application"
+ ]
+ },
+ "DeleteApplication": {
+ "methods": [
+ "delete_application"
+ ]
+ },
+ "GetApplication": {
+ "methods": [
+ "get_application"
+ ]
+ },
+ "ListApplications": {
+ "methods": [
+ "list_applications"
+ ]
+ },
+ "UpdateApplication": {
+ "methods": [
+ "update_application"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "CompanyService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "CompanyServiceClient",
+ "rpcs": {
+ "CreateCompany": {
+ "methods": [
+ "create_company"
+ ]
+ },
+ "DeleteCompany": {
+ "methods": [
+ "delete_company"
+ ]
+ },
+ "GetCompany": {
+ "methods": [
+ "get_company"
+ ]
+ },
+ "ListCompanies": {
+ "methods": [
+ "list_companies"
+ ]
+ },
+ "UpdateCompany": {
+ "methods": [
+ "update_company"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "CompanyServiceAsyncClient",
+ "rpcs": {
+ "CreateCompany": {
+ "methods": [
+ "create_company"
+ ]
+ },
+ "DeleteCompany": {
+ "methods": [
+ "delete_company"
+ ]
+ },
+ "GetCompany": {
+ "methods": [
+ "get_company"
+ ]
+ },
+ "ListCompanies": {
+ "methods": [
+ "list_companies"
+ ]
+ },
+ "UpdateCompany": {
+ "methods": [
+ "update_company"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "Completion": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "CompletionClient",
+ "rpcs": {
+ "CompleteQuery": {
+ "methods": [
+ "complete_query"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "CompletionAsyncClient",
+ "rpcs": {
+ "CompleteQuery": {
+ "methods": [
+ "complete_query"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "EventService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "EventServiceClient",
+ "rpcs": {
+ "CreateClientEvent": {
+ "methods": [
+ "create_client_event"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "EventServiceAsyncClient",
+ "rpcs": {
+ "CreateClientEvent": {
+ "methods": [
+ "create_client_event"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "JobService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "JobServiceClient",
+ "rpcs": {
+ "BatchCreateJobs": {
+ "methods": [
+ "batch_create_jobs"
+ ]
+ },
+ "BatchDeleteJobs": {
+ "methods": [
+ "batch_delete_jobs"
+ ]
+ },
+ "BatchUpdateJobs": {
+ "methods": [
+ "batch_update_jobs"
+ ]
+ },
+ "CreateJob": {
+ "methods": [
+ "create_job"
+ ]
+ },
+ "DeleteJob": {
+ "methods": [
+ "delete_job"
+ ]
+ },
+ "GetJob": {
+ "methods": [
+ "get_job"
+ ]
+ },
+ "ListJobs": {
+ "methods": [
+ "list_jobs"
+ ]
+ },
+ "SearchJobs": {
+ "methods": [
+ "search_jobs"
+ ]
+ },
+ "SearchJobsForAlert": {
+ "methods": [
+ "search_jobs_for_alert"
+ ]
+ },
+ "UpdateJob": {
+ "methods": [
+ "update_job"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "JobServiceAsyncClient",
+ "rpcs": {
+ "BatchCreateJobs": {
+ "methods": [
+ "batch_create_jobs"
+ ]
+ },
+ "BatchDeleteJobs": {
+ "methods": [
+ "batch_delete_jobs"
+ ]
+ },
+ "BatchUpdateJobs": {
+ "methods": [
+ "batch_update_jobs"
+ ]
+ },
+ "CreateJob": {
+ "methods": [
+ "create_job"
+ ]
+ },
+ "DeleteJob": {
+ "methods": [
+ "delete_job"
+ ]
+ },
+ "GetJob": {
+ "methods": [
+ "get_job"
+ ]
+ },
+ "ListJobs": {
+ "methods": [
+ "list_jobs"
+ ]
+ },
+ "SearchJobs": {
+ "methods": [
+ "search_jobs"
+ ]
+ },
+ "SearchJobsForAlert": {
+ "methods": [
+ "search_jobs_for_alert"
+ ]
+ },
+ "UpdateJob": {
+ "methods": [
+ "update_job"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "ProfileService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "ProfileServiceClient",
+ "rpcs": {
+ "CreateProfile": {
+ "methods": [
+ "create_profile"
+ ]
+ },
+ "DeleteProfile": {
+ "methods": [
+ "delete_profile"
+ ]
+ },
+ "GetProfile": {
+ "methods": [
+ "get_profile"
+ ]
+ },
+ "ListProfiles": {
+ "methods": [
+ "list_profiles"
+ ]
+ },
+ "SearchProfiles": {
+ "methods": [
+ "search_profiles"
+ ]
+ },
+ "UpdateProfile": {
+ "methods": [
+ "update_profile"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "ProfileServiceAsyncClient",
+ "rpcs": {
+ "CreateProfile": {
+ "methods": [
+ "create_profile"
+ ]
+ },
+ "DeleteProfile": {
+ "methods": [
+ "delete_profile"
+ ]
+ },
+ "GetProfile": {
+ "methods": [
+ "get_profile"
+ ]
+ },
+ "ListProfiles": {
+ "methods": [
+ "list_profiles"
+ ]
+ },
+ "SearchProfiles": {
+ "methods": [
+ "search_profiles"
+ ]
+ },
+ "UpdateProfile": {
+ "methods": [
+ "update_profile"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "TenantService": {
+ "clients": {
+ "grpc": {
+ "libraryClient": "TenantServiceClient",
+ "rpcs": {
+ "CreateTenant": {
+ "methods": [
+ "create_tenant"
+ ]
+ },
+ "DeleteTenant": {
+ "methods": [
+ "delete_tenant"
+ ]
+ },
+ "GetTenant": {
+ "methods": [
+ "get_tenant"
+ ]
+ },
+ "ListTenants": {
+ "methods": [
+ "list_tenants"
+ ]
+ },
+ "UpdateTenant": {
+ "methods": [
+ "update_tenant"
+ ]
+ }
+ }
+ },
+ "grpc-async": {
+ "libraryClient": "TenantServiceAsyncClient",
+ "rpcs": {
+ "CreateTenant": {
+ "methods": [
+ "create_tenant"
+ ]
+ },
+ "DeleteTenant": {
+ "methods": [
+ "delete_tenant"
+ ]
+ },
+ "GetTenant": {
+ "methods": [
+ "get_tenant"
+ ]
+ },
+ "ListTenants": {
+ "methods": [
+ "list_tenants"
+ ]
+ },
+ "UpdateTenant": {
+ "methods": [
+ "update_tenant"
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/google/cloud/talent_v4beta1/proto/application.proto b/google/cloud/talent_v4beta1/proto/application.proto
deleted file mode 100644
index ccb49208..00000000
--- a/google/cloud/talent_v4beta1/proto/application.proto
+++ /dev/null
@@ -1,183 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/protobuf/timestamp.proto";
-import "google/protobuf/wrappers.proto";
-import "google/type/date.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "ApplicationResourceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// Resource that represents a job application record of a candidate.
-message Application {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Application"
- pattern: "projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}"
- };
-
- // Enum that represents the application status.
- enum ApplicationState {
- // Default value.
- APPLICATION_STATE_UNSPECIFIED = 0;
-
- // The current stage is in progress or pending, for example, interviews in
- // progress.
- IN_PROGRESS = 1;
-
- // The current stage was terminated by a candidate decision.
- CANDIDATE_WITHDREW = 2;
-
- // The current stage was terminated by an employer or agency decision.
- EMPLOYER_WITHDREW = 3;
-
- // The current stage is successfully completed, but the next stage (if
- // applicable) has not begun.
- COMPLETED = 4;
-
- // The current stage was closed without an exception, or terminated for
- // reasons unrealated to the candidate.
- CLOSED = 5;
- }
-
- // The stage of the application.
- enum ApplicationStage {
- // Default value.
- APPLICATION_STAGE_UNSPECIFIED = 0;
-
- // Candidate has applied or a recruiter put candidate into consideration but
- // candidate is not yet screened / no decision has been made to move or not
- // move the candidate to the next stage.
- NEW = 1;
-
- // A recruiter decided to screen the candidate for this role.
- SCREEN = 2;
-
- // Candidate is being / was sent to the customer / hiring manager for
- // detailed review.
- HIRING_MANAGER_REVIEW = 3;
-
- // Candidate was approved by the client / hiring manager and is being / was
- // interviewed for the role.
- INTERVIEW = 4;
-
- // Candidate will be / has been given an offer of employment.
- OFFER_EXTENDED = 5;
-
- // Candidate has accepted their offer of employment.
- OFFER_ACCEPTED = 6;
-
- // Candidate has begun (or completed) their employment or assignment with
- // the employer.
- STARTED = 7;
- }
-
- // Required during application update.
- //
- // Resource name assigned to an application by the API.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}/applications/{application_id}".
- // For example, "projects/foo/tenants/bar/profiles/baz/applications/qux".
- string name = 1;
-
- // Required. Client side application identifier, used to uniquely identify the
- // application.
- //
- // The maximum number of allowed characters is 255.
- string external_id = 31 [(google.api.field_behavior) = REQUIRED];
-
- // Output only. Resource name of the candidate of this application.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
- // For example, "projects/foo/tenants/bar/profiles/baz".
- string profile = 2 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Required. Resource name of the job which the candidate applied for.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}". For example,
- // "projects/foo/tenants/bar/jobs/baz".
- string job = 4 [
- (google.api.resource_reference).type = "jobs.googleapis.com/Job",
- (google.api.field_behavior) = REQUIRED
- ];
-
- // Resource name of the company which the candidate applied for.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}".
- // For example, "projects/foo/tenants/bar/companies/baz".
- string company = 5 [
- (google.api.resource_reference) = { type: "jobs.googleapis.com/Company" }
- ];
-
- // The application date.
- google.type.Date application_date = 7;
-
- // Required. What is the most recent stage of the application (that is, new,
- // screen, send cv, hired, finished work)? This field is intentionally not
- // comprehensive of every possible status, but instead, represents statuses
- // that would be used to indicate to the ML models good / bad matches.
- ApplicationStage stage = 11 [(google.api.field_behavior) = REQUIRED];
-
- // The application state.
- ApplicationState state = 13;
-
- // All interviews (screen, onsite, and so on) conducted as part of this
- // application (includes details such as user conducting the interview,
- // timestamp, feedback, and so on).
- repeated Interview interviews = 16;
-
- // If the candidate is referred by a employee.
- google.protobuf.BoolValue referral = 18;
-
- // Required. Reflects the time that the application was created.
- google.protobuf.Timestamp create_time = 19
- [(google.api.field_behavior) = REQUIRED];
-
- // The last update timestamp.
- google.protobuf.Timestamp update_time = 20;
-
- // Free text reason behind the recruitement outcome (for example, reason for
- // withdraw / reject, reason for an unsuccessful finish, and so on).
- //
- // Number of characters allowed is 100.
- string outcome_notes = 21;
-
- // Outcome positiveness shows how positive the outcome is.
- Outcome outcome = 22;
-
- // Output only. Indicates whether this job application is a match to
- // application related filters. This value is only applicable in profile
- // search response.
- google.protobuf.BoolValue is_match = 28
- [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Job title snippet shows how the job title is related to a
- // search query. It's empty if the job title isn't related to the search
- // query.
- string job_title_snippet = 29 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
diff --git a/google/cloud/talent_v4beta1/proto/application_service.proto b/google/cloud/talent_v4beta1/proto/application_service.proto
deleted file mode 100644
index c9f990da..00000000
--- a/google/cloud/talent_v4beta1/proto/application_service.proto
+++ /dev/null
@@ -1,181 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/application.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "ApplicationServiceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A service that handles application management, including CRUD and
-// enumeration.
-service ApplicationService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Creates a new application entity.
- rpc CreateApplication(CreateApplicationRequest) returns (Application) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*/profiles/*}/applications"
- body: "*"
- };
- option (google.api.method_signature) = "parent,application";
- }
-
- // Retrieves specified application.
- rpc GetApplication(GetApplicationRequest) returns (Application) {
- option (google.api.http) = {
- get: "/v4beta1/{name=projects/*/tenants/*/profiles/*/applications/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates specified application.
- rpc UpdateApplication(UpdateApplicationRequest) returns (Application) {
- option (google.api.http) = {
- patch: "/v4beta1/{application.name=projects/*/tenants/*/profiles/*/applications/*}"
- body: "*"
- };
- option (google.api.method_signature) = "application";
- }
-
- // Deletes specified application.
- rpc DeleteApplication(DeleteApplicationRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4beta1/{name=projects/*/tenants/*/profiles/*/applications/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Lists all applications associated with the profile.
- rpc ListApplications(ListApplicationsRequest) returns (ListApplicationsResponse) {
- option (google.api.http) = {
- get: "/v4beta1/{parent=projects/*/tenants/*/profiles/*}/applications"
- };
- option (google.api.method_signature) = "parent";
- }
-}
-
-// The Request of the CreateApplication method.
-message CreateApplicationRequest {
- // Required. Resource name of the profile under which the application is created.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
- // For example, "projects/foo/tenants/bar/profiles/baz".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Profile"
- }
- ];
-
- // Required. The application to be created.
- Application application = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Request for getting a application by name.
-message GetApplicationRequest {
- // Required. The resource name of the application to be retrieved.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}/applications/{application_id}".
- // For example, "projects/foo/tenants/bar/profiles/baz/applications/qux".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Application"
- }
- ];
-}
-
-// Request for updating a specified application.
-message UpdateApplicationRequest {
- // Required. The application resource to replace the current resource in the system.
- Application application = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // If [update_mask][google.cloud.talent.v4beta1.UpdateApplicationRequest.update_mask] is provided, only the specified fields in
- // [application][google.cloud.talent.v4beta1.UpdateApplicationRequest.application] are updated. Otherwise all the fields are updated.
- //
- // A field mask to specify the application fields to be updated. Only
- // top level fields of [Application][google.cloud.talent.v4beta1.Application] are supported.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Request to delete a application.
-message DeleteApplicationRequest {
- // Required. The resource name of the application to be deleted.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}/applications/{application_id}".
- // For example, "projects/foo/tenants/bar/profiles/baz/applications/qux".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Application"
- }
- ];
-}
-
-// List applications for which the client has ACL visibility.
-message ListApplicationsRequest {
- // Required. Resource name of the profile under which the application is created.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}", for
- // example, "projects/foo/tenants/bar/profiles/baz".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Profile"
- }
- ];
-
- // The starting indicator from which to return results.
- string page_token = 2;
-
- // The maximum number of applications to be returned, at most 100.
- // Default is 100 if a non-positive number is provided.
- int32 page_size = 3;
-}
-
-// The List applications response object.
-message ListApplicationsResponse {
- // Applications for the current client.
- repeated Application applications = 1;
-
- // A token to retrieve the next page of results.
- string next_page_token = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-}
diff --git a/google/cloud/talent_v4beta1/proto/batch.proto b/google/cloud/talent_v4beta1/proto/batch.proto
deleted file mode 100644
index 074e8705..00000000
--- a/google/cloud/talent_v4beta1/proto/batch.proto
+++ /dev/null
@@ -1,25 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "BatchProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
diff --git a/google/cloud/talent_v4beta1/proto/common.proto b/google/cloud/talent_v4beta1/proto/common.proto
deleted file mode 100644
index 13f77421..00000000
--- a/google/cloud/talent_v4beta1/proto/common.proto
+++ /dev/null
@@ -1,1073 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/field_behavior.proto";
-import "google/protobuf/timestamp.proto";
-import "google/protobuf/wrappers.proto";
-import "google/type/date.proto";
-import "google/type/latlng.proto";
-import "google/type/money.proto";
-import "google/type/postal_address.proto";
-import "google/type/timeofday.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CommonProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// Message representing a period of time between two timestamps.
-message TimestampRange {
- // Begin of the period (inclusive).
- google.protobuf.Timestamp start_time = 1;
-
- // End of the period (exclusive).
- google.protobuf.Timestamp end_time = 2;
-}
-
-// A resource that represents a location with full geographic information.
-message Location {
- // An enum which represents the type of a location.
- enum LocationType {
- // Default value if the type isn't specified.
- LOCATION_TYPE_UNSPECIFIED = 0;
-
- // A country level location.
- COUNTRY = 1;
-
- // A state or equivalent level location.
- ADMINISTRATIVE_AREA = 2;
-
- // A county or equivalent level location.
- SUB_ADMINISTRATIVE_AREA = 3;
-
- // A city or equivalent level location.
- LOCALITY = 4;
-
- // A postal code level location.
- POSTAL_CODE = 5;
-
- // A sublocality is a subdivision of a locality, for example a city borough,
- // ward, or arrondissement. Sublocalities are usually recognized by a local
- // political authority. For example, Manhattan and Brooklyn are recognized
- // as boroughs by the City of New York, and are therefore modeled as
- // sublocalities.
- SUB_LOCALITY = 6;
-
- // A district or equivalent level location.
- SUB_LOCALITY_1 = 7;
-
- // A smaller district or equivalent level display.
- SUB_LOCALITY_2 = 8;
-
- // A neighborhood level location.
- NEIGHBORHOOD = 9;
-
- // A street address level location.
- STREET_ADDRESS = 10;
- }
-
- // The type of a location, which corresponds to the address lines field of
- // [google.type.PostalAddress][google.type.PostalAddress]. For example, "Downtown, Atlanta, GA, USA"
- // has a type of [LocationType.NEIGHBORHOOD][google.cloud.talent.v4beta1.Location.LocationType.NEIGHBORHOOD], and "Kansas City, KS, USA"
- // has a type of [LocationType.LOCALITY][google.cloud.talent.v4beta1.Location.LocationType.LOCALITY].
- LocationType location_type = 1;
-
- // Postal address of the location that includes human readable information,
- // such as postal delivery and payments addresses. Given a postal address,
- // a postal service can deliver items to a premises, P.O. Box, or other
- // delivery location.
- google.type.PostalAddress postal_address = 2;
-
- // An object representing a latitude/longitude pair.
- google.type.LatLng lat_lng = 3;
-
- // Radius in miles of the job location. This value is derived from the
- // location bounding box in which a circle with the specified radius
- // centered from [google.type.LatLng][google.type.LatLng] covers the area associated with the
- // job location.
- // For example, currently, "Mountain View, CA, USA" has a radius of
- // 6.17 miles.
- double radius_miles = 4;
-}
-
-// An enum that represents the size of the company.
-enum CompanySize {
- // Default value if the size isn't specified.
- COMPANY_SIZE_UNSPECIFIED = 0;
-
- // The company has less than 50 employees.
- MINI = 1;
-
- // The company has between 50 and 99 employees.
- SMALL = 2;
-
- // The company has between 100 and 499 employees.
- SMEDIUM = 3;
-
- // The company has between 500 and 999 employees.
- MEDIUM = 4;
-
- // The company has between 1,000 and 4,999 employees.
- BIG = 5;
-
- // The company has between 5,000 and 9,999 employees.
- BIGGER = 6;
-
- // The company has 10,000 or more employees.
- GIANT = 7;
-}
-
-// An enum that represents employee benefits included with the job.
-enum JobBenefit {
- // Default value if the type isn't specified.
- JOB_BENEFIT_UNSPECIFIED = 0;
-
- // The job includes access to programs that support child care, such
- // as daycare.
- CHILD_CARE = 1;
-
- // The job includes dental services covered by a dental
- // insurance plan.
- DENTAL = 2;
-
- // The job offers specific benefits to domestic partners.
- DOMESTIC_PARTNER = 3;
-
- // The job allows for a flexible work schedule.
- FLEXIBLE_HOURS = 4;
-
- // The job includes health services covered by a medical insurance plan.
- MEDICAL = 5;
-
- // The job includes a life insurance plan provided by the employer or
- // available for purchase by the employee.
- LIFE_INSURANCE = 6;
-
- // The job allows for a leave of absence to a parent to care for a newborn
- // child.
- PARENTAL_LEAVE = 7;
-
- // The job includes a workplace retirement plan provided by the
- // employer or available for purchase by the employee.
- RETIREMENT_PLAN = 8;
-
- // The job allows for paid time off due to illness.
- SICK_DAYS = 9;
-
- // The job includes paid time off for vacation.
- VACATION = 10;
-
- // The job includes vision services covered by a vision
- // insurance plan.
- VISION = 11;
-}
-
-// Educational degree level defined in International Standard Classification
-// of Education (ISCED).
-enum DegreeType {
- // Default value. Represents no degree, or early childhood education.
- // Maps to ISCED code 0.
- // Ex) Kindergarten
- DEGREE_TYPE_UNSPECIFIED = 0;
-
- // Primary education which is typically the first stage of compulsory
- // education. ISCED code 1.
- // Ex) Elementary school
- PRIMARY_EDUCATION = 1;
-
- // Lower secondary education; First stage of secondary education building on
- // primary education, typically with a more subject-oriented curriculum.
- // ISCED code 2.
- // Ex) Middle school
- LOWER_SECONDARY_EDUCATION = 2;
-
- // Middle education; Second/final stage of secondary education preparing for
- // tertiary education and/or providing skills relevant to employment.
- // Usually with an increased range of subject options and streams. ISCED
- // code 3.
- // Ex) High school
- UPPER_SECONDARY_EDUCATION = 3;
-
- // Adult Remedial Education; Programmes providing learning experiences that
- // build on secondary education and prepare for labour market entry and/or
- // tertiary education. The content is broader than secondary but not as
- // complex as tertiary education. ISCED code 4.
- ADULT_REMEDIAL_EDUCATION = 4;
-
- // Associate's or equivalent; Short first tertiary programmes that are
- // typically practically-based, occupationally-specific and prepare for
- // labour market entry. These programmes may also provide a pathway to other
- // tertiary programmes. ISCED code 5.
- ASSOCIATES_OR_EQUIVALENT = 5;
-
- // Bachelor's or equivalent; Programmes designed to provide intermediate
- // academic and/or professional knowledge, skills and competencies leading
- // to a first tertiary degree or equivalent qualification. ISCED code 6.
- BACHELORS_OR_EQUIVALENT = 6;
-
- // Master's or equivalent; Programmes designed to provide advanced academic
- // and/or professional knowledge, skills and competencies leading to a
- // second tertiary degree or equivalent qualification. ISCED code 7.
- MASTERS_OR_EQUIVALENT = 7;
-
- // Doctoral or equivalent; Programmes designed primarily to lead to an
- // advanced research qualification, usually concluding with the submission
- // and defense of a substantive dissertation of publishable quality based on
- // original research. ISCED code 8.
- DOCTORAL_OR_EQUIVALENT = 8;
-}
-
-// An enum that represents the employment type of a job.
-enum EmploymentType {
- // The default value if the employment type isn't specified.
- EMPLOYMENT_TYPE_UNSPECIFIED = 0;
-
- // The job requires working a number of hours that constitute full
- // time employment, typically 40 or more hours per week.
- FULL_TIME = 1;
-
- // The job entails working fewer hours than a full time job,
- // typically less than 40 hours a week.
- PART_TIME = 2;
-
- // The job is offered as a contracted, as opposed to a salaried employee,
- // position.
- CONTRACTOR = 3;
-
- // The job is offered as a contracted position with the understanding
- // that it's converted into a full-time position at the end of the
- // contract. Jobs of this type are also returned by a search for
- // [EmploymentType.CONTRACTOR][google.cloud.talent.v4beta1.EmploymentType.CONTRACTOR] jobs.
- CONTRACT_TO_HIRE = 4;
-
- // The job is offered as a temporary employment opportunity, usually
- // a short-term engagement.
- TEMPORARY = 5;
-
- // The job is a fixed-term opportunity for students or entry-level job
- // seekers to obtain on-the-job training, typically offered as a summer
- // position.
- INTERN = 6;
-
- // The is an opportunity for an individual to volunteer, where there's no
- // expectation of compensation for the provided services.
- VOLUNTEER = 7;
-
- // The job requires an employee to work on an as-needed basis with a
- // flexible schedule.
- PER_DIEM = 8;
-
- // The job involves employing people in remote areas and flying them
- // temporarily to the work site instead of relocating employees and their
- // families permanently.
- FLY_IN_FLY_OUT = 9;
-
- // The job does not fit any of the other listed types.
- OTHER_EMPLOYMENT_TYPE = 10;
-}
-
-// An enum that represents the required experience level required for the job.
-enum JobLevel {
- // The default value if the level isn't specified.
- JOB_LEVEL_UNSPECIFIED = 0;
-
- // Entry-level individual contributors, typically with less than 2 years of
- // experience in a similar role. Includes interns.
- ENTRY_LEVEL = 1;
-
- // Experienced individual contributors, typically with 2+ years of
- // experience in a similar role.
- EXPERIENCED = 2;
-
- // Entry- to mid-level managers responsible for managing a team of people.
- MANAGER = 3;
-
- // Senior-level managers responsible for managing teams of managers.
- DIRECTOR = 4;
-
- // Executive-level managers and above, including C-level positions.
- EXECUTIVE = 5;
-}
-
-// An enum that represents the categorization or primary focus of specific
-// role. This value is different than the "industry" associated with a role,
-// which is related to the categorization of the company listing the job.
-enum JobCategory {
- // The default value if the category isn't specified.
- JOB_CATEGORY_UNSPECIFIED = 0;
-
- // An accounting and finance job, such as an Accountant.
- ACCOUNTING_AND_FINANCE = 1;
-
- // An administrative and office job, such as an Administrative Assistant.
- ADMINISTRATIVE_AND_OFFICE = 2;
-
- // An advertising and marketing job, such as Marketing Manager.
- ADVERTISING_AND_MARKETING = 3;
-
- // An animal care job, such as Veterinarian.
- ANIMAL_CARE = 4;
-
- // An art, fashion, or design job, such as Designer.
- ART_FASHION_AND_DESIGN = 5;
-
- // A business operations job, such as Business Operations Manager.
- BUSINESS_OPERATIONS = 6;
-
- // A cleaning and facilities job, such as Custodial Staff.
- CLEANING_AND_FACILITIES = 7;
-
- // A computer and IT job, such as Systems Administrator.
- COMPUTER_AND_IT = 8;
-
- // A construction job, such as General Laborer.
- CONSTRUCTION = 9;
-
- // A customer service job, such s Cashier.
- CUSTOMER_SERVICE = 10;
-
- // An education job, such as School Teacher.
- EDUCATION = 11;
-
- // An entertainment and travel job, such as Flight Attendant.
- ENTERTAINMENT_AND_TRAVEL = 12;
-
- // A farming or outdoor job, such as Park Ranger.
- FARMING_AND_OUTDOORS = 13;
-
- // A healthcare job, such as Registered Nurse.
- HEALTHCARE = 14;
-
- // A human resources job, such as Human Resources Director.
- HUMAN_RESOURCES = 15;
-
- // An installation, maintenance, or repair job, such as Electrician.
- INSTALLATION_MAINTENANCE_AND_REPAIR = 16;
-
- // A legal job, such as Law Clerk.
- LEGAL = 17;
-
- // A management job, often used in conjunction with another category,
- // such as Store Manager.
- MANAGEMENT = 18;
-
- // A manufacturing or warehouse job, such as Assembly Technician.
- MANUFACTURING_AND_WAREHOUSE = 19;
-
- // A media, communications, or writing job, such as Media Relations.
- MEDIA_COMMUNICATIONS_AND_WRITING = 20;
-
- // An oil, gas or mining job, such as Offshore Driller.
- OIL_GAS_AND_MINING = 21;
-
- // A personal care and services job, such as Hair Stylist.
- PERSONAL_CARE_AND_SERVICES = 22;
-
- // A protective services job, such as Security Guard.
- PROTECTIVE_SERVICES = 23;
-
- // A real estate job, such as Buyer's Agent.
- REAL_ESTATE = 24;
-
- // A restaurant and hospitality job, such as Restaurant Server.
- RESTAURANT_AND_HOSPITALITY = 25;
-
- // A sales and/or retail job, such Sales Associate.
- SALES_AND_RETAIL = 26;
-
- // A science and engineering job, such as Lab Technician.
- SCIENCE_AND_ENGINEERING = 27;
-
- // A social services or non-profit job, such as Case Worker.
- SOCIAL_SERVICES_AND_NON_PROFIT = 28;
-
- // A sports, fitness, or recreation job, such as Personal Trainer.
- SPORTS_FITNESS_AND_RECREATION = 29;
-
- // A transportation or logistics job, such as Truck Driver.
- TRANSPORTATION_AND_LOGISTICS = 30;
-}
-
-// An enum that represents the job posting region. In most cases, job postings
-// don't need to specify a region. If a region is given, jobs are
-// eligible for searches in the specified region.
-enum PostingRegion {
- // If the region is unspecified, the job is only returned if it
- // matches the [LocationFilter][google.cloud.talent.v4beta1.LocationFilter].
- POSTING_REGION_UNSPECIFIED = 0;
-
- // In addition to exact location matching, job posting is returned when the
- // [LocationFilter][google.cloud.talent.v4beta1.LocationFilter] in the search query is in the same administrative area
- // as the returned job posting. For example, if a `ADMINISTRATIVE_AREA` job
- // is posted in "CA, USA", it's returned if [LocationFilter][google.cloud.talent.v4beta1.LocationFilter] has
- // "Mountain View".
- //
- // Administrative area refers to top-level administrative subdivision of this
- // country. For example, US state, IT region, UK constituent nation and
- // JP prefecture.
- ADMINISTRATIVE_AREA = 1;
-
- // In addition to exact location matching, job is returned when
- // [LocationFilter][google.cloud.talent.v4beta1.LocationFilter] in search query is in the same country as this job.
- // For example, if a `NATION_WIDE` job is posted in "USA", it's
- // returned if [LocationFilter][google.cloud.talent.v4beta1.LocationFilter] has 'Mountain View'.
- NATION = 2;
-
- // Job allows employees to work remotely (telecommute).
- // If locations are provided with this value, the job is
- // considered as having a location, but telecommuting is allowed.
- TELECOMMUTE = 3;
-}
-
-// Deprecated. All resources are only visible to the owner.
-//
-// An enum that represents who has view access to the resource.
-enum Visibility {
- option deprecated = true;
-
- // Default value.
- VISIBILITY_UNSPECIFIED = 0;
-
- // The resource is only visible to the GCP account who owns it.
- ACCOUNT_ONLY = 1;
-
- // The resource is visible to the owner and may be visible to other
- // applications and processes at Google.
- SHARED_WITH_GOOGLE = 2;
-
- // The resource is visible to the owner and may be visible to all other API
- // clients.
- SHARED_WITH_PUBLIC = 3;
-}
-
-// Enum that represents the usage of the contact information.
-enum ContactInfoUsage {
- // Default value.
- CONTACT_INFO_USAGE_UNSPECIFIED = 0;
-
- // Personal use.
- PERSONAL = 1;
-
- // Work use.
- WORK = 2;
-
- // School use.
- SCHOOL = 3;
-}
-
-// Option for HTML content sanitization on user input fields, for example, job
-// description. By setting this option, user can determine whether and how
-// sanitization is performed on these fields.
-enum HtmlSanitization {
- // Default value.
- HTML_SANITIZATION_UNSPECIFIED = 0;
-
- // Disables sanitization on HTML input.
- HTML_SANITIZATION_DISABLED = 1;
-
- // Sanitizes HTML input, only accepts bold, italic, ordered list, and
- // unordered list markup tags.
- SIMPLE_FORMATTING_ONLY = 2;
-}
-
-// Method for commute.
-enum CommuteMethod {
- // Commute method isn't specified.
- COMMUTE_METHOD_UNSPECIFIED = 0;
-
- // Commute time is calculated based on driving time.
- DRIVING = 1;
-
- // Commute time is calculated based on public transit including bus, metro,
- // subway, and so on.
- TRANSIT = 2;
-
- // Commute time is calculated based on walking time.
- WALKING = 3;
-
- // Commute time is calculated based on biking time.
- CYCLING = 4;
-}
-
-// Meta information related to the job searcher or entity
-// conducting the job search. This information is used to improve the
-// performance of the service.
-message RequestMetadata {
- // Required if [allow_missing_ids][google.cloud.talent.v4beta1.RequestMetadata.allow_missing_ids] is unset or `false`.
- //
- // The client-defined scope or source of the service call, which typically
- // is the domain on
- // which the service has been implemented and is currently being run.
- //
- // For example, if the service is being run by client Foo, Inc., on
- // job board www.foo.com and career site www.bar.com, then this field is
- // set to "foo.com" for use on the job board, and "bar.com" for use on the
- // career site.
- //
- // Note that any improvements to the model for a particular tenant site rely
- // on this field being set correctly to a unique domain.
- //
- // The maximum number of allowed characters is 255.
- string domain = 1;
-
- // Required if [allow_missing_ids][google.cloud.talent.v4beta1.RequestMetadata.allow_missing_ids] is unset or `false`.
- //
- // A unique session identification string. A session is defined as the
- // duration of an end user's interaction with the service over a certain
- // period.
- // Obfuscate this field for privacy concerns before
- // providing it to the service.
- //
- // Note that any improvements to the model for a particular tenant site rely
- // on this field being set correctly to a unique session ID.
- //
- // The maximum number of allowed characters is 255.
- string session_id = 2;
-
- // Required if [allow_missing_ids][google.cloud.talent.v4beta1.RequestMetadata.allow_missing_ids] is unset or `false`.
- //
- // A unique user identification string, as determined by the client.
- // To have the strongest positive impact on search quality
- // make sure the client-level is unique.
- // Obfuscate this field for privacy concerns before
- // providing it to the service.
- //
- // Note that any improvements to the model for a particular tenant site rely
- // on this field being set correctly to a unique user ID.
- //
- // The maximum number of allowed characters is 255.
- string user_id = 3;
-
- // Only set when any of [domain][google.cloud.talent.v4beta1.RequestMetadata.domain], [session_id][google.cloud.talent.v4beta1.RequestMetadata.session_id] and [user_id][google.cloud.talent.v4beta1.RequestMetadata.user_id] isn't
- // available for some reason. It is highly recommended not to set this field
- // and provide accurate [domain][google.cloud.talent.v4beta1.RequestMetadata.domain], [session_id][google.cloud.talent.v4beta1.RequestMetadata.session_id] and [user_id][google.cloud.talent.v4beta1.RequestMetadata.user_id] for the
- // best service experience.
- bool allow_missing_ids = 4;
-
- // The type of device used by the job seeker at the time of the call to the
- // service.
- DeviceInfo device_info = 5;
-}
-
-// Additional information returned to client, such as debugging information.
-message ResponseMetadata {
- // A unique id associated with this call.
- // This id is logged for tracking purposes.
- string request_id = 1;
-}
-
-// Device information collected from the job seeker, candidate, or
-// other entity conducting the job search. Providing this information improves
-// the quality of the search results across devices.
-message DeviceInfo {
- // An enumeration describing an API access portal and exposure mechanism.
- enum DeviceType {
- // The device type isn't specified.
- DEVICE_TYPE_UNSPECIFIED = 0;
-
- // A desktop web browser, such as, Chrome, Firefox, Safari, or Internet
- // Explorer)
- WEB = 1;
-
- // A mobile device web browser, such as a phone or tablet with a Chrome
- // browser.
- MOBILE_WEB = 2;
-
- // An Android device native application.
- ANDROID = 3;
-
- // An iOS device native application.
- IOS = 4;
-
- // A bot, as opposed to a device operated by human beings, such as a web
- // crawler.
- BOT = 5;
-
- // Other devices types.
- OTHER = 6;
- }
-
- // Type of the device.
- DeviceType device_type = 1;
-
- // A device-specific ID. The ID must be a unique identifier that
- // distinguishes the device from other devices.
- string id = 2;
-}
-
-// Custom attribute values that are either filterable or non-filterable.
-message CustomAttribute {
- // Exactly one of [string_values][google.cloud.talent.v4beta1.CustomAttribute.string_values] or [long_values][google.cloud.talent.v4beta1.CustomAttribute.long_values] must be specified.
- //
- // This field is used to perform a string match (`CASE_SENSITIVE_MATCH` or
- // `CASE_INSENSITIVE_MATCH`) search.
- // For filterable `string_value`s, a maximum total number of 200 values
- // is allowed, with each `string_value` has a byte size of no more than
- // 500B. For unfilterable `string_values`, the maximum total byte size of
- // unfilterable `string_values` is 50KB.
- //
- // Empty string isn't allowed.
- repeated string string_values = 1;
-
- // Exactly one of [string_values][google.cloud.talent.v4beta1.CustomAttribute.string_values] or [long_values][google.cloud.talent.v4beta1.CustomAttribute.long_values] must be specified.
- //
- // This field is used to perform number range search.
- // (`EQ`, `GT`, `GE`, `LE`, `LT`) over filterable `long_value`.
- //
- // Currently at most 1 [long_values][google.cloud.talent.v4beta1.CustomAttribute.long_values] is supported.
- repeated int64 long_values = 2;
-
- // If the `filterable` flag is true, custom field values are searchable.
- // If false, values are not searchable.
- //
- // Default is false.
- bool filterable = 3;
-}
-
-// Spell check result.
-message SpellingCorrection {
- // Indicates if the query was corrected by the spell checker.
- bool corrected = 1;
-
- // Correction output consisting of the corrected keyword string.
- string corrected_text = 2;
-
- // Corrected output with html tags to highlight the corrected words.
- // Corrected words are called out with the "..." html tags.
- //
- // For example, the user input query is "software enginear", where the second
- // word, "enginear," is incorrect. It should be "engineer". When spelling
- // correction is enabled, this value is
- // "software engineer".
- string corrected_html = 3;
-}
-
-// Job compensation details.
-message CompensationInfo {
- // A compensation entry that represents one component of compensation, such
- // as base pay, bonus, or other compensation type.
- //
- // Annualization: One compensation entry can be annualized if
- // - it contains valid [amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount] or [range][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.range].
- // - and its [expected_units_per_year][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.expected_units_per_year] is set or can be derived.
- // Its annualized range is determined as ([amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount] or [range][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.range]) times
- // [expected_units_per_year][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.expected_units_per_year].
- message CompensationEntry {
- // Compensation type.
- //
- // Default is [CompensationType.COMPENSATION_TYPE_UNSPECIFIED][google.cloud.talent.v4beta1.CompensationInfo.CompensationType.COMPENSATION_TYPE_UNSPECIFIED].
- CompensationType type = 1;
-
- // Frequency of the specified amount.
- //
- // Default is [CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED].
- CompensationUnit unit = 2;
-
- // Compensation amount. It could be a fixed amount or a floating range.
- oneof compensation_amount {
- // Compensation amount.
- google.type.Money amount = 3;
-
- // Compensation range.
- CompensationRange range = 4;
- }
-
- // Compensation description. For example, could
- // indicate equity terms or provide additional context to an estimated
- // bonus.
- string description = 5;
-
- // Expected number of units paid each year. If not specified, when
- // [Job.employment_types][google.cloud.talent.v4beta1.Job.employment_types] is FULLTIME, a default value is inferred
- // based on [unit][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.unit]. Default values:
- // - HOURLY: 2080
- // - DAILY: 260
- // - WEEKLY: 52
- // - MONTHLY: 12
- // - ANNUAL: 1
- google.protobuf.DoubleValue expected_units_per_year = 6;
- }
-
- // Compensation range.
- message CompensationRange {
- // The maximum amount of compensation. If left empty, the value is set
- // to a maximal compensation value and the currency code is set to
- // match the [currency code][google.type.Money.currency_code] of
- // min_compensation.
- google.type.Money max_compensation = 2;
-
- // The minimum amount of compensation. If left empty, the value is set
- // to zero and the currency code is set to match the
- // [currency code][google.type.Money.currency_code] of max_compensation.
- google.type.Money min_compensation = 1;
- }
-
- // The type of compensation.
- //
- // For compensation amounts specified in non-monetary amounts,
- // describe the compensation scheme in the [CompensationEntry.description][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.description].
- //
- // For example, tipping format is described in
- // [CompensationEntry.description][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.description] (for example, "expect 15-20% tips based
- // on customer bill.") and an estimate of the tips provided in
- // [CompensationEntry.amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount] or [CompensationEntry.range][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.range] ($10 per hour).
- //
- // For example, equity is described in [CompensationEntry.description][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.description]
- // (for example, "1% - 2% equity vesting over 4 years, 1 year cliff") and
- // value estimated in [CompensationEntry.amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount] or
- // [CompensationEntry.range][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.range]. If no value estimate is possible, units are
- // [CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED] and then further
- // clarified in [CompensationEntry.description][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.description] field.
- enum CompensationType {
- // Default value.
- COMPENSATION_TYPE_UNSPECIFIED = 0;
-
- // Base compensation: Refers to the fixed amount of money paid to an
- // employee by an employer in return for work performed. Base compensation
- // does not include benefits, bonuses or any other potential compensation
- // from an employer.
- BASE = 1;
-
- // Bonus.
- BONUS = 2;
-
- // Signing bonus.
- SIGNING_BONUS = 3;
-
- // Equity.
- EQUITY = 4;
-
- // Profit sharing.
- PROFIT_SHARING = 5;
-
- // Commission.
- COMMISSIONS = 6;
-
- // Tips.
- TIPS = 7;
-
- // Other compensation type.
- OTHER_COMPENSATION_TYPE = 8;
- }
-
- // Pay frequency.
- enum CompensationUnit {
- // Default value.
- COMPENSATION_UNIT_UNSPECIFIED = 0;
-
- // Hourly.
- HOURLY = 1;
-
- // Daily.
- DAILY = 2;
-
- // Weekly
- WEEKLY = 3;
-
- // Monthly.
- MONTHLY = 4;
-
- // Yearly.
- YEARLY = 5;
-
- // One time.
- ONE_TIME = 6;
-
- // Other compensation units.
- OTHER_COMPENSATION_UNIT = 7;
- }
-
- // Job compensation information.
- //
- // At most one entry can be of type
- // [CompensationInfo.CompensationType.BASE][google.cloud.talent.v4beta1.CompensationInfo.CompensationType.BASE], which is
- // referred as **base compensation entry** for the job.
- repeated CompensationEntry entries = 1;
-
- // Output only. Annualized base compensation range. Computed as base compensation entry's
- // [CompensationEntry.amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount] times
- // [CompensationEntry.expected_units_per_year][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.expected_units_per_year].
- //
- // See [CompensationEntry][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry] for explanation on compensation annualization.
- CompensationRange annualized_base_compensation_range = 2 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Annualized total compensation range. Computed as all compensation entries'
- // [CompensationEntry.amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount] times
- // [CompensationEntry.expected_units_per_year][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.expected_units_per_year].
- //
- // See [CompensationEntry][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry] for explanation on compensation annualization.
- CompensationRange annualized_total_compensation_range = 3 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
-
-// Resource that represents a license or certification.
-message Certification {
- // Name of license or certification.
- //
- // Number of characters allowed is 100.
- string display_name = 1;
-
- // Acquisition date or effective date of license or certification.
- google.type.Date acquire_date = 2;
-
- // Expiration date of license of certification.
- google.type.Date expire_date = 3;
-
- // Authority of license, such as government.
- //
- // Number of characters allowed is 100.
- string authority = 4;
-
- // Description of license or certification.
- //
- // Number of characters allowed is 100,000.
- string description = 5;
-}
-
-// Resource that represents a skill of a candidate.
-message Skill {
- // Skill display name.
- //
- // For example, "Java", "Python".
- //
- // Number of characters allowed is 100.
- string display_name = 1;
-
- // The last time this skill was used.
- google.type.Date last_used_date = 2;
-
- // Skill proficiency level which indicates how proficient the candidate is at
- // this skill.
- SkillProficiencyLevel level = 3;
-
- // A paragraph describes context of this skill.
- //
- // Number of characters allowed is 100,000.
- string context = 4;
-
- // Output only. Skill name snippet shows how the [display_name][google.cloud.talent.v4beta1.Skill.display_name] is related to a search
- // query. It's empty if the [display_name][google.cloud.talent.v4beta1.Skill.display_name] isn't related to the search
- // query.
- string skill_name_snippet = 5 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
-
-// Details of an interview.
-message Interview {
- // The rating on this interview.
- Rating rating = 6;
-
- // Required. The overall decision resulting from this interview (positive, negative,
- // nuetral).
- Outcome outcome = 7 [(google.api.field_behavior) = REQUIRED];
-}
-
-// The details of the score received for an assessment or interview.
-message Rating {
- // Overall score.
- double overall = 1;
-
- // The minimum value for the score.
- double min = 2;
-
- // The maximum value for the score.
- double max = 3;
-
- // The steps within the score (for example, interval = 1 max = 5
- // min = 1 indicates that the score can be 1, 2, 3, 4, or 5)
- double interval = 4;
-}
-
-// Metadata used for long running operations returned by CTS batch APIs.
-// It's used to replace [google.longrunning.Operation.metadata][google.longrunning.Operation.metadata].
-message BatchOperationMetadata {
- enum State {
- // Default value.
- STATE_UNSPECIFIED = 0;
-
- // The batch operation is being prepared for processing.
- INITIALIZING = 1;
-
- // The batch operation is actively being processed.
- PROCESSING = 2;
-
- // The batch operation is processed, and at least one item has been
- // successfully processed.
- SUCCEEDED = 3;
-
- // The batch operation is done and no item has been successfully processed.
- FAILED = 4;
-
- // The batch operation is in the process of cancelling after
- // [google.longrunning.Operations.CancelOperation][google.longrunning.Operations.CancelOperation] is called.
- CANCELLING = 5;
-
- // The batch operation is done after
- // [google.longrunning.Operations.CancelOperation][google.longrunning.Operations.CancelOperation] is called. Any items
- // processed before cancelling are returned in the response.
- CANCELLED = 6;
- }
-
- // The state of a long running operation.
- State state = 1;
-
- // More detailed information about operation state.
- string state_description = 2;
-
- // Count of successful item(s) inside an operation.
- int32 success_count = 3;
-
- // Count of failed item(s) inside an operation.
- int32 failure_count = 4;
-
- // Count of total item(s) inside an operation.
- int32 total_count = 5;
-
- // The time when the batch operation is created.
- google.protobuf.Timestamp create_time = 6;
-
- // The time when the batch operation status is updated. The metadata and the
- // [update_time][google.cloud.talent.v4beta1.BatchOperationMetadata.update_time] is refreshed every minute otherwise cached data is
- // returned.
- google.protobuf.Timestamp update_time = 7;
-
- // The time when the batch operation is finished and
- // [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to `true`.
- google.protobuf.Timestamp end_time = 8;
-}
-
-// Enum that represents the skill proficiency level.
-enum SkillProficiencyLevel {
- // Default value.
- SKILL_PROFICIENCY_LEVEL_UNSPECIFIED = 0;
-
- // Lacks any proficiency in this skill.
- UNSKILLED = 6;
-
- // Have a common knowledge or an understanding of basic techniques and
- // concepts.
- FUNDAMENTAL_AWARENESS = 1;
-
- // Have the level of experience gained in a classroom and/or experimental
- // scenarios or as a trainee on-the-job.
- NOVICE = 2;
-
- // Be able to successfully complete tasks in this skill as requested. Help
- // from an expert may be required from time to time, but can usually perform
- // skill independently.
- INTERMEDIATE = 3;
-
- // Can perform the actions associated with this skill without assistance.
- ADVANCED = 4;
-
- // Known as an expert in this area.
- EXPERT = 5;
-}
-
-// The overall outcome /decision / result indicator.
-enum Outcome {
- // Default value.
- OUTCOME_UNSPECIFIED = 0;
-
- // A positive outcome / passing indicator (for example, candidate was
- // recommended for hiring or to be moved forward in the hiring process,
- // candidate passed a test).
- POSITIVE = 1;
-
- // A neutral outcome / no clear indicator (for example, no strong
- // reccommendation either to move forward / not move forward, neutral score).
- NEUTRAL = 2;
-
- // A negative outcome / failing indicator (for example, candidate was
- // recommended to NOT move forward in the hiring process, failed a test).
- NEGATIVE = 3;
-
- // The assessment outcome is not available or otherwise unknown (for example,
- // candidate did not complete assessment).
- OUTCOME_NOT_AVAILABLE = 4;
-}
-
-// The type of candidate availability signal.
-enum AvailabilitySignalType {
- // Default value.
- AVAILABILITY_SIGNAL_TYPE_UNSPECIFIED = 0;
-
- // Job application signal.
- //
- // In the context of [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals], this signal is related
- // to the candidate's most recent application.
- // [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is
- // calculated from max([Application.create_time][google.cloud.talent.v4beta1.Application.create_time]) from all [Application][google.cloud.talent.v4beta1.Application]
- // records where [Application.source][google.cloud.talent.v4beta1.Application.source] is any of the following:
- // [APPLY_DIRECT_WEB][google.cloud.talent.v4beta1.Application.ApplicationSource.APPLY_DIRECT_WEB]
- // [APPLY_DIRECT_MOBILE_WEB][google.cloud.talent.v4beta1.Application.ApplicationSource.APPLY_DIRECT_MOBILE_WEB]
- // [APPLY_DIRECT_MOBILE_APP][google.cloud.talent.v4beta1.Application.ApplicationSource.APPLY_DIRECT_MOBILE_APP]
- // [APPLY_DIRECT_IN_PERSON][google.cloud.talent.v4beta1.Application.ApplicationSource.APPLY_DIRECT_IN_PERSON]
- // [APPLY_INDIRECT][google.cloud.talent.v4beta1.Application.ApplicationSource.APPLY_INDIRECT]
- //
- // In the context of [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter], the filter is applied on
- // [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals] where
- // [type][google.cloud.talent.v4beta1.AvailabilitySignal.type] is JOB_APPLICATION.
- JOB_APPLICATION = 1;
-
- // Resume update signal.
- //
- // In the context of [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals], this signal is related
- // to the candidate's most recent update to their resume.
- // For a [SummarizedProfile.summary][google.cloud.talent.v4beta1.SummarizedProfile.summary],
- // [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is
- // calculated from max([Profile.resume_update_time][google.cloud.talent.v4beta1.Profile.resume_update_time]) from all
- // [SummarizedProfile.profiles][google.cloud.talent.v4beta1.SummarizedProfile.profiles].
- //
- // In the context of [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter], the filter is applied on
- // [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals] where
- // [type][google.cloud.talent.v4beta1.AvailabilitySignal.type] is RESUME_UPDATE.
- RESUME_UPDATE = 2;
-
- // Candidate update signal.
- //
- // In the context of [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals], this signal is related
- // to the candidate's most recent update to their profile.
- // For a [SummarizedProfile.summary][google.cloud.talent.v4beta1.SummarizedProfile.summary],
- // [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is
- // calculated from max([Profile.candidate_update_time][google.cloud.talent.v4beta1.Profile.candidate_update_time]) from all
- // [SummarizedProfile.profiles][google.cloud.talent.v4beta1.SummarizedProfile.profiles].
- //
- // In the context of [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter], the filter is applied on
- // [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals] where
- // [type][google.cloud.talent.v4beta1.AvailabilitySignal.type] is CANDIDATE_UPDATE.
- CANDIDATE_UPDATE = 3;
-
- // Client submission signal.
- //
- // In the context of [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals], this signal is related
- // to the candidate's most recent submission.
- // [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is
- // calculated from max([Application.create_time][google.cloud.talent.v4beta1.Application.create_time]) from all [Application][google.cloud.talent.v4beta1.Application]
- // records where [Application.stage][google.cloud.talent.v4beta1.Application.stage] is any of the following:
- // [HIRING_MANAGER_REVIEW][google.cloud.talent.v4beta1.Application.ApplicationStage.HIRING_MANAGER_REVIEW]
- // [INTERVIEW][google.cloud.talent.v4beta1.Application.ApplicationStage.INTERVIEW]
- // [OFFER_EXTENDED][google.cloud.talent.v4beta1.Application.ApplicationStage.OFFER_EXTENDED]
- // [OFFER_ACCEPTED][google.cloud.talent.v4beta1.Application.ApplicationStage.OFFER_ACCEPTED]
- // [STARTED][google.cloud.talent.v4beta1.Application.ApplicationStage.STARTED]
- //
- // In the context of [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter], the filter is applied on
- // [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals] where
- // [type][google.cloud.talent.v4beta1.AvailabilitySignal.type] is CLIENT_SUBMISSION.
- CLIENT_SUBMISSION = 4;
-}
diff --git a/google/cloud/talent_v4beta1/proto/company.proto b/google/cloud/talent_v4beta1/proto/company.proto
deleted file mode 100644
index c6894572..00000000
--- a/google/cloud/talent_v4beta1/proto/company.proto
+++ /dev/null
@@ -1,119 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CompanyResourceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A Company resource represents a company in the service. A company is the
-// entity that owns job postings, that is, the hiring entity responsible for
-// employing applicants for the job position.
-message Company {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Company"
- pattern: "projects/{project}/tenants/{tenant}/companies/{company}"
- pattern: "projects/{project}/companies/{company}"
- };
-
- // Derived details about the company.
- message DerivedInfo {
- // A structured headquarters location of the company, resolved from
- // [Company.headquarters_address][google.cloud.talent.v4beta1.Company.headquarters_address] if provided.
- Location headquarters_location = 1;
- }
-
- // Required during company update.
- //
- // The resource name for a company. This is generated by the service when a
- // company is created.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/foo/tenants/bar/companies/baz".
- //
- // If tenant id is unspecified, the default tenant is used. For
- // example, "projects/foo/companies/bar".
- string name = 1;
-
- // Required. The display name of the company, for example, "Google LLC".
- string display_name = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Required. Client side company identifier, used to uniquely identify the
- // company.
- //
- // The maximum number of allowed characters is 255.
- string external_id = 3 [(google.api.field_behavior) = REQUIRED];
-
- // The employer's company size.
- CompanySize size = 4;
-
- // The street address of the company's main headquarters, which may be
- // different from the job location. The service attempts
- // to geolocate the provided address, and populates a more specific
- // location wherever possible in [DerivedInfo.headquarters_location][google.cloud.talent.v4beta1.Company.DerivedInfo.headquarters_location].
- string headquarters_address = 5;
-
- // Set to true if it is the hiring agency that post jobs for other
- // employers.
- //
- // Defaults to false if not provided.
- bool hiring_agency = 6;
-
- // Equal Employment Opportunity legal disclaimer text to be
- // associated with all jobs, and typically to be displayed in all
- // roles.
- //
- // The maximum number of allowed characters is 500.
- string eeo_text = 7;
-
- // The URI representing the company's primary web site or home page,
- // for example, "https://www.google.com".
- //
- // The maximum number of allowed characters is 255.
- string website_uri = 8;
-
- // The URI to employer's career site or careers page on the employer's web
- // site, for example, "https://careers.google.com".
- string career_site_uri = 9;
-
- // A URI that hosts the employer's company logo.
- string image_uri = 10;
-
- // A list of keys of filterable [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes], whose
- // corresponding `string_values` are used in keyword searches. Jobs with
- // `string_values` under these specified field keys are returned if any
- // of the values match the search keyword. Custom field values with
- // parenthesis, brackets and special symbols are not searchable as-is,
- // and those keyword queries must be surrounded by quotes.
- repeated string keyword_searchable_job_custom_attributes = 11;
-
- // Output only. Derived details about the company.
- DerivedInfo derived_info = 12 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Indicates whether a company is flagged to be suspended from
- // public availability by the service when job content appears suspicious,
- // abusive, or spammy.
- bool suspended = 13 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
diff --git a/google/cloud/talent_v4beta1/proto/company_service.proto b/google/cloud/talent_v4beta1/proto/company_service.proto
deleted file mode 100644
index ac6a7d74..00000000
--- a/google/cloud/talent_v4beta1/proto/company_service.proto
+++ /dev/null
@@ -1,214 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/cloud/talent/v4beta1/company.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CompanyServiceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A service that handles company management, including CRUD and enumeration.
-service CompanyService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Creates a new company entity.
- rpc CreateCompany(CreateCompanyRequest) returns (Company) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/companies"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/companies"
- body: "*"
- }
- };
- option (google.api.method_signature) = "parent,company";
- }
-
- // Retrieves specified company.
- rpc GetCompany(GetCompanyRequest) returns (Company) {
- option (google.api.http) = {
- get: "/v4beta1/{name=projects/*/tenants/*/companies/*}"
- additional_bindings {
- get: "/v4beta1/{name=projects/*/companies/*}"
- }
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates specified company.
- rpc UpdateCompany(UpdateCompanyRequest) returns (Company) {
- option (google.api.http) = {
- patch: "/v4beta1/{company.name=projects/*/tenants/*/companies/*}"
- body: "*"
- additional_bindings {
- patch: "/v4beta1/{company.name=projects/*/companies/*}"
- body: "*"
- }
- };
- option (google.api.method_signature) = "company";
- }
-
- // Deletes specified company.
- // Prerequisite: The company has no jobs associated with it.
- rpc DeleteCompany(DeleteCompanyRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4beta1/{name=projects/*/tenants/*/companies/*}"
- additional_bindings {
- delete: "/v4beta1/{name=projects/*/companies/*}"
- }
- };
- option (google.api.method_signature) = "name";
- }
-
- // Lists all companies associated with the project.
- rpc ListCompanies(ListCompaniesRequest) returns (ListCompaniesResponse) {
- option (google.api.http) = {
- get: "/v4beta1/{parent=projects/*/tenants/*}/companies"
- additional_bindings {
- get: "/v4beta1/{parent=projects/*}/companies"
- }
- };
- option (google.api.method_signature) = "parent";
- }
-}
-
-// The Request of the CreateCompany method.
-message CreateCompanyRequest {
- // Required. Resource name of the tenant under which the company is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
- // is created, for example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Company"
- }
- ];
-
- // Required. The company to be created.
- Company company = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Request for getting a company by name.
-message GetCompanyRequest {
- // Required. The resource name of the company to be retrieved.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/api-test-project/tenants/foo/companies/bar".
- //
- // If tenant id is unspecified, the default tenant is used, for
- // example, "projects/api-test-project/companies/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }
- ];
-}
-
-// Request for updating a specified company.
-message UpdateCompanyRequest {
- // Required. The company resource to replace the current resource in the system.
- Company company = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // If [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask] is provided, only the specified fields in
- // [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are updated. Otherwise all the fields are updated.
- //
- // A field mask to specify the company fields to be updated. Only
- // top level fields of [Company][google.cloud.talent.v4beta1.Company] are supported.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Request to delete a company.
-message DeleteCompanyRequest {
- // Required. The resource name of the company to be deleted.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/foo/tenants/bar/companies/baz".
- //
- // If tenant id is unspecified, the default tenant is used, for
- // example, "projects/foo/companies/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }
- ];
-}
-
-// List companies for which the client has ACL visibility.
-message ListCompaniesRequest {
- // Required. Resource name of the tenant under which the company is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenant/bar".
- //
- // If tenant id is unspecified, the default tenant will be used, for
- // example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Company"
- }
- ];
-
- // The starting indicator from which to return results.
- string page_token = 2;
-
- // The maximum number of companies to be returned, at most 100.
- // Default is 100 if a non-positive number is provided.
- int32 page_size = 3;
-
- // Set to true if the companies requested must have open jobs.
- //
- // Defaults to false.
- //
- // If true, at most [page_size][google.cloud.talent.v4beta1.ListCompaniesRequest.page_size] of companies are fetched, among which
- // only those with open jobs are returned.
- bool require_open_jobs = 4;
-}
-
-// The List companies response object.
-message ListCompaniesResponse {
- // Companies for the current client.
- repeated Company companies = 1;
-
- // A token to retrieve the next page of results.
- string next_page_token = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-}
diff --git a/google/cloud/talent_v4beta1/proto/completion_service.proto b/google/cloud/talent_v4beta1/proto/completion_service.proto
deleted file mode 100644
index 2e45ac7d..00000000
--- a/google/cloud/talent_v4beta1/proto/completion_service.proto
+++ /dev/null
@@ -1,163 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/api/client.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "CompletionServiceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A service handles auto completion.
-service Completion {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Completes the specified prefix with keyword suggestions.
- // Intended for use by a job search auto-complete search box.
- rpc CompleteQuery(CompleteQueryRequest) returns (CompleteQueryResponse) {
- option (google.api.http) = {
- get: "/v4beta1/{parent=projects/*/tenants/*}:complete"
- additional_bindings {
- get: "/v4beta1/{parent=projects/*}:complete"
- }
- };
- }
-}
-
-// Auto-complete parameters.
-message CompleteQueryRequest {
- // Enum to specify the scope of completion.
- enum CompletionScope {
- // Default value.
- COMPLETION_SCOPE_UNSPECIFIED = 0;
-
- // Suggestions are based only on the data provided by the client.
- TENANT = 1;
-
- // Suggestions are based on all jobs data in the system that's visible to
- // the client
- PUBLIC = 2;
- }
-
- // Enum to specify auto-completion topics.
- enum CompletionType {
- // Default value.
- COMPLETION_TYPE_UNSPECIFIED = 0;
-
- // Suggest job titles for jobs autocomplete.
- //
- // For [CompletionType.JOB_TITLE][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionType.JOB_TITLE] type, only open jobs with the same
- // [language_codes][google.cloud.talent.v4beta1.CompleteQueryRequest.language_codes] are returned.
- JOB_TITLE = 1;
-
- // Suggest company names for jobs autocomplete.
- //
- // For [CompletionType.COMPANY_NAME][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionType.COMPANY_NAME] type,
- // only companies having open jobs with the same [language_codes][google.cloud.talent.v4beta1.CompleteQueryRequest.language_codes] are
- // returned.
- COMPANY_NAME = 2;
-
- // Suggest both job titles and company names for jobs autocomplete.
- //
- // For [CompletionType.COMBINED][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionType.COMBINED] type, only open jobs with the same
- // [language_codes][google.cloud.talent.v4beta1.CompleteQueryRequest.language_codes] or companies having open jobs with the same
- // [language_codes][google.cloud.talent.v4beta1.CompleteQueryRequest.language_codes] are returned.
- COMBINED = 3;
- }
-
- // Required. Resource name of tenant the completion is performed within.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenant/bar".
- //
- // If tenant id is unspecified, the default tenant is used, for
- // example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Company"
- }
- ];
-
- // Required. The query used to generate suggestions.
- //
- // The maximum number of allowed characters is 255.
- string query = 2 [(google.api.field_behavior) = REQUIRED];
-
- // The list of languages of the query. This is
- // the BCP-47 language code, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47).
- //
- // The maximum number of allowed characters is 255.
- repeated string language_codes = 3;
-
- // Required. Completion result count.
- //
- // The maximum allowed page size is 10.
- int32 page_size = 4 [(google.api.field_behavior) = REQUIRED];
-
- // If provided, restricts completion to specified company.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}", for
- // example, "projects/foo/tenants/bar/companies/baz".
- //
- // If tenant id is unspecified, the default tenant is used, for
- // example, "projects/foo".
- string company = 5 [(google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }];
-
- // The scope of the completion. The defaults is [CompletionScope.PUBLIC][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionScope.PUBLIC].
- CompletionScope scope = 6;
-
- // The completion topic. The default is [CompletionType.COMBINED][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionType.COMBINED].
- CompletionType type = 7;
-}
-
-// Response of auto-complete query.
-message CompleteQueryResponse {
- // Resource that represents completion results.
- message CompletionResult {
- // The suggestion for the query.
- string suggestion = 1;
-
- // The completion topic.
- CompleteQueryRequest.CompletionType type = 2;
-
- // The URI of the company image for
- // [COMPANY_NAME][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionType.COMPANY_NAME].
- string image_uri = 3;
- }
-
- // Results of the matching job/company candidates.
- repeated CompletionResult completion_results = 1;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 2;
-}
diff --git a/google/cloud/talent_v4beta1/proto/event.proto b/google/cloud/talent_v4beta1/proto/event.proto
deleted file mode 100644
index c5a71553..00000000
--- a/google/cloud/talent_v4beta1/proto/event.proto
+++ /dev/null
@@ -1,234 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/field_behavior.proto";
-import "google/protobuf/timestamp.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "EventProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// An event issued when an end user interacts with the application that
-// implements Cloud Talent Solution. Providing this information improves the
-// quality of results for the API clients, enabling the
-// service to perform optimally. The number of events sent must be consistent
-// with other calls, such as job searches, issued to the service by the client.
-message ClientEvent {
- // Strongly recommended for the best service experience.
- //
- // A unique ID generated in the API responses. It can be found in
- // [ResponseMetadata.request_id][google.cloud.talent.v4beta1.ResponseMetadata.request_id].
- string request_id = 1;
-
- // Required. A unique identifier, generated by the client application.
- string event_id = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The timestamp of the event.
- google.protobuf.Timestamp create_time = 4 [(google.api.field_behavior) = REQUIRED];
-
- // Required.
- //
- // The detail information of a specific event type.
- oneof event {
- // An event issued when a job seeker interacts with the application that
- // implements Cloud Talent Solution.
- JobEvent job_event = 5;
-
- // An event issued when a profile searcher interacts with the application
- // that implements Cloud Talent Solution.
- ProfileEvent profile_event = 6;
- }
-
- // Notes about the event provided by recruiters or other users, for example,
- // feedback on why a profile was bookmarked.
- string event_notes = 9;
-}
-
-// An event issued when a job seeker interacts with the application that
-// implements Cloud Talent Solution.
-message JobEvent {
- // An enumeration of an event attributed to the behavior of the end user,
- // such as a job seeker.
- enum JobEventType {
- // The event is unspecified by other provided values.
- JOB_EVENT_TYPE_UNSPECIFIED = 0;
-
- // The job seeker or other entity interacting with the service has
- // had a job rendered in their view, such as in a list of search results in
- // a compressed or clipped format. This event is typically associated with
- // the viewing of a jobs list on a single page by a job seeker.
- IMPRESSION = 1;
-
- // The job seeker, or other entity interacting with the service, has
- // viewed the details of a job, including the full description. This
- // event doesn't apply to the viewing a snippet of a job appearing as a
- // part of the job search results. Viewing a snippet is associated with an
- // [impression][google.cloud.talent.v4beta1.JobEvent.JobEventType.IMPRESSION]).
- VIEW = 2;
-
- // The job seeker or other entity interacting with the service
- // performed an action to view a job and was redirected to a different
- // website for job.
- VIEW_REDIRECT = 3;
-
- // The job seeker or other entity interacting with the service
- // began the process or demonstrated the intention of applying for a job.
- APPLICATION_START = 4;
-
- // The job seeker or other entity interacting with the service
- // submitted an application for a job.
- APPLICATION_FINISH = 5;
-
- // The job seeker or other entity interacting with the service
- // submitted an application for a job with a single click without
- // entering information. If a job seeker performs this action, send only
- // this event to the service. Do not also send
- // [JobEventType.APPLICATION_START][google.cloud.talent.v4beta1.JobEvent.JobEventType.APPLICATION_START] or [JobEventType.APPLICATION_FINISH][google.cloud.talent.v4beta1.JobEvent.JobEventType.APPLICATION_FINISH]
- // events.
- APPLICATION_QUICK_SUBMISSION = 6;
-
- // The job seeker or other entity interacting with the service
- // performed an action to apply to a job and was redirected to a different
- // website to complete the application.
- APPLICATION_REDIRECT = 7;
-
- // The job seeker or other entity interacting with the service began the
- // process or demonstrated the intention of applying for a job from the
- // search results page without viewing the details of the job posting.
- // If sending this event, JobEventType.VIEW event shouldn't be sent.
- APPLICATION_START_FROM_SEARCH = 8;
-
- // The job seeker, or other entity interacting with the service, performs an
- // action with a single click from the search results page to apply to a job
- // (without viewing the details of the job posting), and is redirected
- // to a different website to complete the application. If a candidate
- // performs this action, send only this event to the service. Do not also
- // send [JobEventType.APPLICATION_START][google.cloud.talent.v4beta1.JobEvent.JobEventType.APPLICATION_START],
- // [JobEventType.APPLICATION_FINISH][google.cloud.talent.v4beta1.JobEvent.JobEventType.APPLICATION_FINISH] or [JobEventType.VIEW][google.cloud.talent.v4beta1.JobEvent.JobEventType.VIEW] events.
- APPLICATION_REDIRECT_FROM_SEARCH = 9;
-
- // This event should be used when a company submits an application
- // on behalf of a job seeker. This event is intended for use by staffing
- // agencies attempting to place candidates.
- APPLICATION_COMPANY_SUBMIT = 10;
-
- // The job seeker or other entity interacting with the service demonstrated
- // an interest in a job by bookmarking or saving it.
- BOOKMARK = 11;
-
- // The job seeker or other entity interacting with the service was
- // sent a notification, such as an email alert or device notification,
- // containing one or more jobs listings generated by the service.
- NOTIFICATION = 12;
-
- // The job seeker or other entity interacting with the service was
- // employed by the hiring entity (employer). Send this event
- // only if the job seeker was hired through an application that was
- // initiated by a search conducted through the Cloud Talent Solution
- // service.
- HIRED = 13;
-
- // A recruiter or staffing agency submitted an application on behalf of the
- // candidate after interacting with the service to identify a suitable job
- // posting.
- SENT_CV = 14;
-
- // The entity interacting with the service (for example, the job seeker),
- // was granted an initial interview by the hiring entity (employer). This
- // event should only be sent if the job seeker was granted an interview as
- // part of an application that was initiated by a search conducted through /
- // recommendation provided by the Cloud Talent Solution service.
- INTERVIEW_GRANTED = 15;
- }
-
- // Required. The type of the event (see [JobEventType][google.cloud.talent.v4beta1.JobEvent.JobEventType]).
- JobEventType type = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The [job name(s)][google.cloud.talent.v4beta1.Job.name] associated with this event.
- // For example, if this is an [impression][google.cloud.talent.v4beta1.JobEvent.JobEventType.IMPRESSION] event,
- // this field contains the identifiers of all jobs shown to the job seeker.
- // If this was a [view][google.cloud.talent.v4beta1.JobEvent.JobEventType.VIEW] event, this field contains the
- // identifier of the viewed job.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}", for
- // example, "projects/foo/tenants/bar/jobs/baz".
- repeated string jobs = 2 [(google.api.field_behavior) = REQUIRED];
-
- // The [profile name][google.cloud.talent.v4beta1.Profile.name] associated with this client event.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}",
- // for example, "projects/foo/tenants/bar/profiles/baz".
- string profile = 3;
-}
-
-// An event issued when a profile searcher interacts with the application
-// that implements Cloud Talent Solution.
-message ProfileEvent {
- // The enum represents types of client events for a candidate profile.
- enum ProfileEventType {
- // Default value.
- PROFILE_EVENT_TYPE_UNSPECIFIED = 0;
-
- // Send this event when a [ProfileEvent.profiles][google.cloud.talent.v4beta1.ProfileEvent.profiles] was sent as a part of
- // a result set for a CTS API call and was rendered in the end user's UI
- // (that is, the [ProfileEvent.recruiter][google.cloud.talent.v4beta1.ProfileEvent.recruiter]).
- IMPRESSION = 1;
-
- // The VIEW event records the action of a candidate's profile being
- // viewed by an end user. This is critical to tracking product metrics and
- // should be sent for every profile VIEW that happens in your system,
- // whether the event is associated with an API call (for example, a
- // recruiter making a request for a result set and clicking on a profile)
- // or not (a recruiter using the system to view profile details without
- // making a request).
- //
- // For a VIEW events associated with API calls, the
- // [ClientEvent.request_id][google.cloud.talent.v4beta1.ClientEvent.request_id] should be populated. If the VIEW is not
- // associated with an API call, [request_id][google.cloud.talent.v4beta1.ClientEvent.request_id] should
- // not be populated.
- //
- // This event requires a valid recruiter and one valid ID in profiles.
- VIEW = 2;
-
- // The profile is bookmarked.
- BOOKMARK = 3;
- }
-
- // Required. Type of event.
- ProfileEventType type = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The [profile name(s)][google.cloud.talent.v4beta1.Profile.name] associated with this client event.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}",
- // for example, "projects/foo/tenants/bar/profiles/baz".
- repeated string profiles = 2 [(google.api.field_behavior) = REQUIRED];
-
- // The [job name(s)][google.cloud.talent.v4beta1.Job.name] associated with this client event. Leave it
- // empty if the event isn't associated with a job.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}", for
- // example, "projects/foo/tenants/bar/jobs/baz".
- repeated string jobs = 6;
-}
diff --git a/google/cloud/talent_v4beta1/proto/event_service.proto b/google/cloud/talent_v4beta1/proto/event_service.proto
deleted file mode 100644
index 4577352e..00000000
--- a/google/cloud/talent_v4beta1/proto/event_service.proto
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/event.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "EventServiceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A service handles client event report.
-service EventService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Report events issued when end user interacts with customer's application
- // that uses Cloud Talent Solution. You may inspect the created events in
- // [self service
- // tools](https://console.cloud.google.com/talent-solution/overview).
- // [Learn
- // more](https://cloud.google.com/talent-solution/docs/management-tools)
- // about self service tools.
- rpc CreateClientEvent(CreateClientEventRequest) returns (ClientEvent) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/clientEvents"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/clientEvents"
- body: "*"
- }
- };
- option (google.api.method_signature) = "parent,client_event";
- }
-}
-
-// The report event request.
-message CreateClientEventRequest {
- // Required. Resource name of the tenant under which the event is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
- // is created, for example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Company"
- }
- ];
-
- // Required. Events issued when end user interacts with customer's application that
- // uses Cloud Talent Solution.
- ClientEvent client_event = 2 [(google.api.field_behavior) = REQUIRED];
-}
diff --git a/google/cloud/talent_v4beta1/proto/filters.proto b/google/cloud/talent_v4beta1/proto/filters.proto
deleted file mode 100644
index a8cebd7e..00000000
--- a/google/cloud/talent_v4beta1/proto/filters.proto
+++ /dev/null
@@ -1,780 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/field_behavior.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/protobuf/duration.proto";
-import "google/protobuf/field_mask.proto";
-import "google/protobuf/timestamp.proto";
-import "google/protobuf/wrappers.proto";
-import "google/type/date.proto";
-import "google/type/latlng.proto";
-import "google/type/timeofday.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "FiltersProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// The query required to perform a search query.
-message JobQuery {
- // The query string that matches against the job title, description, and
- // location fields.
- //
- // The maximum number of allowed characters is 255.
- string query = 1;
-
- // The language code of [query][google.cloud.talent.v4beta1.JobQuery.query]. For example, "en-US". This field helps to
- // better interpret the query.
- //
- // If a value isn't specified, the query language code is automatically
- // detected, which may not be accurate.
- //
- // Language code should be in BCP-47 format, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47).
- string query_language_code = 14;
-
- // This filter specifies the company entities to search against.
- //
- // If a value isn't specified, jobs are searched for against all
- // companies.
- //
- // If multiple values are specified, jobs are searched against the
- // companies specified.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}". For
- // example, "projects/foo/tenants/bar/companies/baz".
- //
- // If tenant id is unspecified, the default tenant is used. For
- // example, "projects/foo/companies/bar".
- //
- // At most 20 company filters are allowed.
- repeated string companies = 2;
-
- // The location filter specifies geo-regions containing the jobs to
- // search against. See [LocationFilter][google.cloud.talent.v4beta1.LocationFilter] for more information.
- //
- // If a location value isn't specified, jobs fitting the other search
- // criteria are retrieved regardless of where they're located.
- //
- // If multiple values are specified, jobs are retrieved from any of the
- // specified locations. If different values are specified for the
- // [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] parameter, the maximum provided
- // distance is used for all locations.
- //
- // At most 5 location filters are allowed.
- repeated LocationFilter location_filters = 3;
-
- // The category filter specifies the categories of jobs to search against.
- // See [JobCategory][google.cloud.talent.v4beta1.JobCategory] for more information.
- //
- // If a value isn't specified, jobs from any category are searched against.
- //
- // If multiple values are specified, jobs from any of the specified
- // categories are searched against.
- repeated JobCategory job_categories = 4;
-
- // Allows filtering jobs by commute time with different travel methods (for
- // example, driving or public transit).
- //
- // Note: This only works when you specify a [CommuteMethod][google.cloud.talent.v4beta1.CommuteMethod]. In this case,
- // [location_filters][google.cloud.talent.v4beta1.JobQuery.location_filters] is ignored.
- //
- // Currently we don't support sorting by commute time.
- CommuteFilter commute_filter = 5;
-
- // This filter specifies the exact company [Company.display_name][google.cloud.talent.v4beta1.Company.display_name]
- // of the jobs to search against.
- //
- // If a value isn't specified, jobs within the search results are
- // associated with any company.
- //
- // If multiple values are specified, jobs within the search results may be
- // associated with any of the specified companies.
- //
- // At most 20 company display name filters are allowed.
- repeated string company_display_names = 6;
-
- // This search filter is applied only to
- // [Job.compensation_info][google.cloud.talent.v4beta1.Job.compensation_info]. For example, if the filter is specified
- // as "Hourly job with per-hour compensation > $15", only jobs meeting
- // these criteria are searched. If a filter isn't defined, all open jobs
- // are searched.
- CompensationFilter compensation_filter = 7;
-
- // This filter specifies a structured syntax to match against the
- // [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes] marked as `filterable`.
- //
- // The syntax for this expression is a subset of SQL syntax.
- //
- // Supported operators are: `=`, `!=`, `<`, `<=`, `>`, and `>=` where the
- // left of the operator is a custom field key and the right of the operator
- // is a number or a quoted string. You must escape backslash (\\) and
- // quote (\") characters.
- //
- // Supported functions are `LOWER([field_name])` to
- // perform a case insensitive match and `EMPTY([field_name])` to filter on the
- // existence of a key.
- //
- // Boolean expressions (AND/OR/NOT) are supported up to 3 levels of
- // nesting (for example, "((A AND B AND C) OR NOT D) AND E"), a maximum of 100
- // comparisons or functions are allowed in the expression. The expression
- // must be < 6000 bytes in length.
- //
- // Sample Query:
- // `(LOWER(driving_license)="class \"a\"" OR EMPTY(driving_license)) AND
- // driving_years > 10`
- string custom_attribute_filter = 8;
-
- // This flag controls the spell-check feature. If false, the
- // service attempts to correct a misspelled query,
- // for example, "enginee" is corrected to "engineer".
- //
- // Defaults to false: a spell check is performed.
- bool disable_spell_check = 9;
-
- // The employment type filter specifies the employment type of jobs to
- // search against, such as [EmploymentType.FULL_TIME][google.cloud.talent.v4beta1.EmploymentType.FULL_TIME].
- //
- // If a value isn't specified, jobs in the search results includes any
- // employment type.
- //
- // If multiple values are specified, jobs in the search results include
- // any of the specified employment types.
- repeated EmploymentType employment_types = 10;
-
- // This filter specifies the locale of jobs to search against,
- // for example, "en-US".
- //
- // If a value isn't specified, the search results can contain jobs in any
- // locale.
- //
- //
- // Language codes should be in BCP-47 format, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47).
- //
- // At most 10 language code filters are allowed.
- repeated string language_codes = 11;
-
- // Jobs published within a range specified by this filter are searched
- // against.
- TimestampRange publish_time_range = 12;
-
- // This filter specifies a list of job names to be excluded during search.
- //
- // At most 400 excluded job names are allowed.
- repeated string excluded_jobs = 13;
-}
-
-// Filters to apply when performing the search query.
-message ProfileQuery {
- // Keywords to match any text fields of profiles.
- //
- // For example, "software engineer in Palo Alto".
- string query = 1;
-
- // The location filter specifies geo-regions containing the profiles to
- // search against.
- //
- // One of [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] or [LocationFilter.lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] must be
- // provided or an error is thrown. If both [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] and
- // [LocationFilter.lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] are provided, an error is thrown.
- //
- // The following logic is used to determine which locations in
- // the profile to filter against:
- //
- // 1. All of the profile's geocoded [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where
- // [Address.usage][google.cloud.talent.v4beta1.Address.usage] is PERSONAL and [Address.current][google.cloud.talent.v4beta1.Address.current] is true.
- //
- // 2. If the above set of locations is empty, all of the profile's geocoded
- // [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where [Address.usage][google.cloud.talent.v4beta1.Address.usage] is
- // CONTACT_INFO_USAGE_UNSPECIFIED and [Address.current][google.cloud.talent.v4beta1.Address.current] is true.
- //
- // 3. If the above set of locations is empty, all of the profile's geocoded
- // [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where [Address.usage][google.cloud.talent.v4beta1.Address.usage] is PERSONAL or
- // CONTACT_INFO_USAGE_UNSPECIFIED and [Address.current][google.cloud.talent.v4beta1.Address.current] is not set.
- //
- // This means that any profiles without any [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] that match
- // any of the above criteria will not be included in a search with location
- // filter. Furthermore, any [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] where [Address.usage][google.cloud.talent.v4beta1.Address.usage] is
- // WORK or SCHOOL or where [Address.current][google.cloud.talent.v4beta1.Address.current] is false are not considered for
- // location filter.
- //
- // If a location filter isn't specified, profiles fitting the other search
- // criteria are retrieved regardless of where they're located.
- //
- // If [LocationFilter.negated][google.cloud.talent.v4beta1.LocationFilter.negated] is specified, the result doesn't contain
- // profiles from that location.
- //
- // If [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] is provided, the
- // [LocationType][google.cloud.talent.v4beta1.Location.LocationType], center
- // point (latitude and longitude), and radius are automatically detected by
- // the Google Maps Geocoding API and included as well. If
- // [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] cannot be geocoded, the filter
- // falls back to keyword search.
- //
- // If the detected
- // [LocationType][google.cloud.talent.v4beta1.Location.LocationType] is
- // [LocationType.SUB_ADMINISTRATIVE_AREA][google.cloud.talent.v4beta1.Location.LocationType.SUB_ADMINISTRATIVE_AREA],
- // [LocationType.ADMINISTRATIVE_AREA][google.cloud.talent.v4beta1.Location.LocationType.ADMINISTRATIVE_AREA],
- // or
- // [LocationType.COUNTRY][google.cloud.talent.v4beta1.Location.LocationType.COUNTRY],
- // the filter is performed against the detected location name (using exact
- // text matching). Otherwise, the filter is performed against the detected
- // center point and a radius of detected location radius +
- // [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles].
- //
- // If [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address] is provided,
- // [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] is the additional radius on top of the
- // radius of the location geocoded from [LocationFilter.address][google.cloud.talent.v4beta1.LocationFilter.address]. If
- // [LocationFilter.lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] is provided,
- // [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] is the only radius that is used.
- //
- // [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] is 10 by default. Note that the value
- // of [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] is 0 if it is unset, so the server
- // does not differentiate [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] that is
- // explicitly set to 0 and [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] that is not
- // set. Which means that if [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] is explicitly
- // set to 0, the server will use the default value of
- // [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] which is 10. To work around this and
- // effectively set [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] to 0, we recommend
- // setting [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] to a very small decimal number
- // (such as 0.00001).
- //
- // If [LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles] is negative, an error is thrown.
- repeated LocationFilter location_filters = 2;
-
- // Job title filter specifies job titles of profiles to match on.
- //
- // If a job title isn't specified, profiles with any titles are retrieved.
- //
- // If multiple values are specified, profiles are retrieved with any of the
- // specified job titles.
- //
- // If [JobTitleFilter.negated][google.cloud.talent.v4beta1.JobTitleFilter.negated] is specified, the result won't contain
- // profiles with the job titles.
- //
- // For example, search for profiles with a job title "Product Manager".
- repeated JobTitleFilter job_title_filters = 3;
-
- // Employer filter specifies employers of profiles to match on.
- //
- // If an employer filter isn't specified, profiles with any employers are
- // retrieved.
- //
- // If multiple employer filters are specified, profiles with any matching
- // employers are retrieved.
- //
- // If [EmployerFilter.negated][google.cloud.talent.v4beta1.EmployerFilter.negated] is specified, the result won't contain
- // profiles that match the employers.
- //
- // For example, search for profiles that have working experience at "Google
- // LLC".
- repeated EmployerFilter employer_filters = 4;
-
- // Education filter specifies education of profiles to match on.
- //
- // If an education filter isn't specified, profiles with any education are
- // retrieved.
- //
- // If multiple education filters are specified, profiles that match any
- // education filters are retrieved.
- //
- // If [EducationFilter.negated][google.cloud.talent.v4beta1.EducationFilter.negated] is specified, the result won't contain
- // profiles that match the educations.
- //
- // For example, search for profiles with a master degree.
- repeated EducationFilter education_filters = 5;
-
- // Skill filter specifies skill of profiles to match on.
- //
- // If a skill filter isn't specified, profiles with any skills are retrieved.
- //
- // If multiple skill filters are specified, profiles that match any skill
- // filters are retrieved.
- //
- // If [SkillFilter.negated][google.cloud.talent.v4beta1.SkillFilter.negated] is specified, the result won't contain profiles
- // that match the skills.
- //
- // For example, search for profiles that have "Java" and "Python" in skill
- // list.
- repeated SkillFilter skill_filters = 6;
-
- // Work experience filter specifies the total working experience of profiles
- // to match on.
- //
- // If a work experience filter isn't specified, profiles with any
- // professional experience are retrieved.
- //
- // If multiple work experience filters are specified, profiles that match any
- // work experience filters are retrieved.
- //
- // For example, search for profiles with 10 years of work experience.
- repeated WorkExperienceFilter work_experience_filter = 7;
-
- // Time filter specifies the create/update timestamp of the profiles to match
- // on.
- //
- // For example, search for profiles created since "2018-1-1".
- repeated TimeFilter time_filters = 8;
-
- // The hirable filter specifies the profile's hirable status to match on.
- google.protobuf.BoolValue hirable_filter = 9;
-
- // The application date filters specify application date ranges to match on.
- repeated ApplicationDateFilter application_date_filters = 10;
-
- // The application outcome notes filters specify the notes for the outcome of
- // the job application.
- repeated ApplicationOutcomeNotesFilter application_outcome_notes_filters = 11;
-
- // The application job filters specify the job applied for in the application.
- repeated ApplicationJobFilter application_job_filters = 13;
-
- // This filter specifies a structured syntax to match against the
- // [Profile.custom_attributes][google.cloud.talent.v4beta1.Profile.custom_attributes] that are marked as `filterable`.
- //
- // The syntax for this expression is a subset of Google SQL syntax.
- //
- // String custom attributes: supported operators are =, != where the left of
- // the operator is a custom field key and the right of the operator is a
- // string (surrounded by quotes) value.
- //
- // Numeric custom attributes: Supported operators are '>', '<' or '='
- // operators where the left of the operator is a custom field key and the
- // right of the operator is a numeric value.
- //
- // Supported functions are LOWER() to
- // perform case insensitive match and EMPTY() to filter on the
- // existence of a key.
- //
- // Boolean expressions (AND/OR/NOT) are supported up to 3 levels of
- // nesting (for example "((A AND B AND C) OR NOT D) AND E"), and there can be
- // a maximum of 50 comparisons/functions in the expression. The expression
- // must be < 2000 characters in length.
- //
- // Sample Query:
- // (key1 = "TEST" OR LOWER(key1)="test" OR NOT EMPTY(key1))
- string custom_attribute_filter = 15;
-
- // Deprecated. Use availability_filters instead.
- //
- // The candidate availability filter which filters based on availability
- // signals.
- //
- // Signal 1: Number of days since most recent job application. See
- // [Availability.JobApplicationAvailabilitySignal][google.cloud.talent.v4beta1.Availability.JobApplicationAvailabilitySignal] for the details of this
- // signal.
- //
- // Signal 2: Number of days since last profile update. See
- // [Availability.ProfileUpdateAvailabilitySignal][google.cloud.talent.v4beta1.Availability.ProfileUpdateAvailabilitySignal]
- // for the details of this signal.
- //
- // The candidate availability filter helps a recruiter understand if a
- // specific candidate is likely to be actively seeking new job opportunities
- // based on an aggregated set of signals. Specifically, the intent is NOT to
- // indicate the candidate's potential qualification / interest / close ability
- // for a specific job.
- CandidateAvailabilityFilter candidate_availability_filter = 16 [deprecated = true];
-
- // The availability filter which filters based on
- // [Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals].
- //
- // The availability filter helps a recruiter understand if a
- // specific candidate is likely to be actively seeking new job opportunities
- // based on an aggregated set of signals. Specifically, the intent is NOT to
- // indicate the candidate's potential qualification / interest / close ability
- // for a specific job.
- //
- // There can be at most one [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter] per
- // [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type]. If there are multiple
- // [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter] for a [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type],
- // an error is thrown.
- repeated AvailabilityFilter availability_filters = 18;
-
- // Person name filter specifies person name of profiles to match on.
- //
- // If multiple person name filters are specified, profiles that match any
- // person name filters are retrieved.
- //
- // For example, search for profiles of candidates with name "John Smith".
- repeated PersonNameFilter person_name_filters = 17;
-}
-
-// Geographic region of the search.
-message LocationFilter {
- // Specify whether to include telecommute jobs.
- enum TelecommutePreference {
- // Default value if the telecommute preference isn't specified.
- TELECOMMUTE_PREFERENCE_UNSPECIFIED = 0;
-
- // Exclude telecommute jobs.
- TELECOMMUTE_EXCLUDED = 1;
-
- // Allow telecommute jobs.
- TELECOMMUTE_ALLOWED = 2;
- }
-
- // The address name, such as "Mountain View" or "Bay Area".
- string address = 1;
-
- // CLDR region code of the country/region of the address. This is used
- // to address ambiguity of the user-input location, for example, "Liverpool"
- // against "Liverpool, NY, US" or "Liverpool, UK".
- //
- // Set this field to bias location resolution toward a specific country
- // or territory. If this field is not set, application behavior is biased
- // toward the United States by default.
- //
- // See
- // https://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
- // for details. Example: "CH" for Switzerland.
- // Note that this filter is not applicable for Profile Search related queries.
- string region_code = 2;
-
- // The latitude and longitude of the geographic center to search from. This
- // field is ignored if `address` is provided.
- google.type.LatLng lat_lng = 3;
-
- // The distance_in_miles is applied when the location being searched for is
- // identified as a city or smaller. This field is ignored if the location
- // being searched for is a state or larger.
- double distance_in_miles = 4;
-
- // Allows the client to return jobs without a
- // set location, specifically, telecommuting jobs (telecommuting is considered
- // by the service as a special location.
- // [Job.posting_region][google.cloud.talent.v4beta1.Job.posting_region] indicates if a job permits telecommuting.
- // If this field is set to [TelecommutePreference.TELECOMMUTE_ALLOWED][google.cloud.talent.v4beta1.LocationFilter.TelecommutePreference.TELECOMMUTE_ALLOWED],
- // telecommuting jobs are searched, and [address][google.cloud.talent.v4beta1.LocationFilter.address] and [lat_lng][google.cloud.talent.v4beta1.LocationFilter.lat_lng] are
- // ignored. If not set or set to
- // [TelecommutePreference.TELECOMMUTE_EXCLUDED][google.cloud.talent.v4beta1.LocationFilter.TelecommutePreference.TELECOMMUTE_EXCLUDED], telecommute job are not
- // searched.
- //
- // This filter can be used by itself to search exclusively for telecommuting
- // jobs, or it can be combined with another location
- // filter to search for a combination of job locations,
- // such as "Mountain View" or "telecommuting" jobs. However, when used in
- // combination with other location filters, telecommuting jobs can be
- // treated as less relevant than other jobs in the search response.
- //
- // This field is only used for job search requests.
- TelecommutePreference telecommute_preference = 5;
-
- // Whether to apply negation to the filter so profiles matching the filter
- // are excluded.
- //
- // Currently only supported in profile search.
- bool negated = 6;
-}
-
-// Filter on job compensation type and amount.
-message CompensationFilter {
- // Specify the type of filtering.
- enum FilterType {
- // Filter type unspecified. Position holder, INVALID, should never be used.
- FILTER_TYPE_UNSPECIFIED = 0;
-
- // Filter by `base compensation entry's` unit. A job is a match if and
- // only if the job contains a base CompensationEntry and the base
- // CompensationEntry's unit matches provided [units][google.cloud.talent.v4beta1.CompensationFilter.units].
- // Populate one or more [units][google.cloud.talent.v4beta1.CompensationFilter.units].
- //
- // See [CompensationInfo.CompensationEntry][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry] for definition of
- // base compensation entry.
- UNIT_ONLY = 1;
-
- // Filter by `base compensation entry's` unit and amount / range. A job
- // is a match if and only if the job contains a base CompensationEntry, and
- // the base entry's unit matches provided
- // [CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit] and
- // amount or range overlaps with provided
- // [CompensationRange][google.cloud.talent.v4beta1.CompensationInfo.CompensationRange].
- //
- // See [CompensationInfo.CompensationEntry][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry] for definition of
- // base compensation entry.
- //
- // Set exactly one [units][google.cloud.talent.v4beta1.CompensationFilter.units] and populate [range][google.cloud.talent.v4beta1.CompensationFilter.range].
- UNIT_AND_AMOUNT = 2;
-
- // Filter by annualized base compensation amount and `base compensation
- // entry's` unit. Populate [range][google.cloud.talent.v4beta1.CompensationFilter.range] and zero or more [units][google.cloud.talent.v4beta1.CompensationFilter.units].
- ANNUALIZED_BASE_AMOUNT = 3;
-
- // Filter by annualized total compensation amount and `base compensation
- // entry's` unit . Populate [range][google.cloud.talent.v4beta1.CompensationFilter.range] and zero or more [units][google.cloud.talent.v4beta1.CompensationFilter.units].
- ANNUALIZED_TOTAL_AMOUNT = 4;
- }
-
- // Required. Type of filter.
- FilterType type = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. Specify desired `base compensation entry's`
- // [CompensationInfo.CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit].
- repeated CompensationInfo.CompensationUnit units = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Compensation range.
- CompensationInfo.CompensationRange range = 3;
-
- // If set to true, jobs with unspecified compensation range fields are
- // included.
- bool include_jobs_with_unspecified_compensation_range = 4;
-}
-
-// Parameters needed for commute search.
-message CommuteFilter {
- // The traffic density to use when calculating commute time.
- enum RoadTraffic {
- // Road traffic situation isn't specified.
- ROAD_TRAFFIC_UNSPECIFIED = 0;
-
- // Optimal commute time without considering any traffic impact.
- TRAFFIC_FREE = 1;
-
- // Commute time calculation takes in account the peak traffic impact.
- BUSY_HOUR = 2;
- }
-
- // Required. The method of transportation to calculate the commute time for.
- CommuteMethod commute_method = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The latitude and longitude of the location to calculate the
- // commute time from.
- google.type.LatLng start_coordinates = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The maximum travel time in seconds. The maximum allowed value is `3600s`
- // (one hour). Format is `123s`.
- google.protobuf.Duration travel_duration = 3 [(google.api.field_behavior) = REQUIRED];
-
- // If `true`, jobs without street level addresses may also be returned.
- // For city level addresses, the city center is used. For state and coarser
- // level addresses, text matching is used.
- // If this field is set to `false` or isn't specified, only jobs that include
- // street level addresses will be returned by commute search.
- bool allow_imprecise_addresses = 4;
-
- // Traffic factor to take into account while searching by commute.
- oneof traffic_option {
- // Specifies the traffic density to use when calculating commute time.
- RoadTraffic road_traffic = 5;
-
- // The departure time used to calculate traffic impact, represented as
- // [google.type.TimeOfDay][google.type.TimeOfDay] in local time zone.
- //
- // Currently traffic model is restricted to hour level resolution.
- google.type.TimeOfDay departure_time = 6;
- }
-}
-
-// Job title of the search.
-message JobTitleFilter {
- // Required. The job title. For example, "Software engineer", or "Product manager".
- string job_title = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Whether to apply negation to the filter so profiles matching the filter
- // are excluded.
- bool negated = 2;
-}
-
-// Skill filter of the search.
-message SkillFilter {
- // Required. The skill name. For example, "java", "j2ee", and so on.
- string skill = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Whether to apply negation to the filter so profiles matching the filter
- // are excluded.
- bool negated = 2;
-}
-
-// Employer filter of the search.
-message EmployerFilter {
- // Enum indicating which set of [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records] to search
- // against.
- enum EmployerFilterMode {
- // Default value.
- EMPLOYER_FILTER_MODE_UNSPECIFIED = 0;
-
- // Apply to all employers in [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records].
- ALL_EMPLOYMENT_RECORDS = 1;
-
- // Apply only to current employer in [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records].
- CURRENT_EMPLOYMENT_RECORDS_ONLY = 2;
-
- // Apply only to past (not current) employers in
- // [Profile.employment_records][google.cloud.talent.v4beta1.Profile.employment_records].
- PAST_EMPLOYMENT_RECORDS_ONLY = 3;
- }
-
- // Required. The name of the employer, for example "Google", "Alphabet".
- string employer = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Define set of [EmploymentRecord][google.cloud.talent.v4beta1.EmploymentRecord]s to search against.
- //
- // Defaults to [EmployerFilterMode.ALL_EMPLOYMENT_RECORDS][google.cloud.talent.v4beta1.EmployerFilter.EmployerFilterMode.ALL_EMPLOYMENT_RECORDS].
- EmployerFilterMode mode = 2;
-
- // Whether to apply negation to the filter so profiles matching the filter
- // is excluded.
- bool negated = 3;
-}
-
-// Education filter of the search.
-message EducationFilter {
- // The school name. For example "MIT", "University of California, Berkeley".
- string school = 1;
-
- // The field of study. This is to search against value provided in
- // [Degree.fields_of_study][google.cloud.talent.v4beta1.Degree.fields_of_study].
- // For example "Computer Science", "Mathematics".
- string field_of_study = 2;
-
- // Education degree in ISCED code. Each value in degree covers a specific
- // level of education, without any expansion to upper nor lower levels of
- // education degree.
- DegreeType degree_type = 3;
-
- // Whether to apply negation to the filter so profiles matching the filter
- // is excluded.
- bool negated = 6;
-}
-
-// Work experience filter.
-//
-// This filter is used to search for profiles with working experience length
-// between [min_experience][google.cloud.talent.v4beta1.WorkExperienceFilter.min_experience] and [max_experience][google.cloud.talent.v4beta1.WorkExperienceFilter.max_experience].
-message WorkExperienceFilter {
- // The minimum duration of the work experience (inclusive).
- google.protobuf.Duration min_experience = 1;
-
- // The maximum duration of the work experience (exclusive).
- google.protobuf.Duration max_experience = 2;
-}
-
-// Application Date Range Filter.
-//
-// The API matches profiles with [Application.application_date][google.cloud.talent.v4beta1.Application.application_date] between
-// start date and end date (both boundaries are inclusive). The filter is
-// ignored if both [start_date][google.cloud.talent.v4beta1.ApplicationDateFilter.start_date] and [end_date][google.cloud.talent.v4beta1.ApplicationDateFilter.end_date] are missing.
-message ApplicationDateFilter {
- // Start date. If it's missing, The API matches profiles with application date
- // not after the end date.
- google.type.Date start_date = 1;
-
- // End date. If it's missing, The API matches profiles with application date
- // not before the start date.
- google.type.Date end_date = 2;
-}
-
-// Outcome Notes Filter.
-message ApplicationOutcomeNotesFilter {
- // Required. User entered or selected outcome reason. The API does an exact match on the
- // [Application.outcome_notes][google.cloud.talent.v4beta1.Application.outcome_notes] in profiles.
- string outcome_notes = 1 [(google.api.field_behavior) = REQUIRED];
-
- // If true, The API excludes all candidates with any
- // [Application.outcome_notes][google.cloud.talent.v4beta1.Application.outcome_notes] matching the outcome reason specified in
- // the filter.
- bool negated = 2;
-}
-
-// Filter on the job information of Application.
-message ApplicationJobFilter {
- // The job requisition id in the application. The API does an exact match on
- // the [Job.requisition_id][google.cloud.talent.v4beta1.Job.requisition_id] of [Application.job][google.cloud.talent.v4beta1.Application.job] in profiles.
- string job_requisition_id = 2;
-
- // The job title in the application. The API does an exact match on the
- // [Job.title][google.cloud.talent.v4beta1.Job.title] of [Application.job][google.cloud.talent.v4beta1.Application.job] in profiles.
- string job_title = 3;
-
- // If true, the API excludes all profiles with any [Application.job][google.cloud.talent.v4beta1.Application.job]
- // matching the filters.
- bool negated = 4;
-}
-
-// Filter on create timestamp or update timestamp of profiles.
-message TimeFilter {
- // Time fields can be used in TimeFilter.
- enum TimeField {
- // Default value.
- TIME_FIELD_UNSPECIFIED = 0;
-
- // Earliest profile create time.
- CREATE_TIME = 1;
-
- // Latest profile update time.
- UPDATE_TIME = 2;
- }
-
- // Start timestamp, matching profiles with the start time. If this field
- // missing, The API matches profiles with create / update timestamp before the
- // end timestamp.
- google.protobuf.Timestamp start_time = 1;
-
- // End timestamp, matching profiles with the end time. If this field
- // missing, The API matches profiles with create / update timestamp after the
- // start timestamp.
- google.protobuf.Timestamp end_time = 2;
-
- // Specifies which time field to filter profiles.
- //
- // Defaults to [TimeField.CREATE_TIME][google.cloud.talent.v4beta1.TimeFilter.TimeField.CREATE_TIME].
- TimeField time_field = 3;
-}
-
-// Deprecated. Use AvailabilityFilter instead.
-//
-// Filter on availability signals.
-message CandidateAvailabilityFilter {
- option deprecated = true;
-
- // It is false by default. If true, API excludes all the potential available
- // profiles.
- bool negated = 1;
-}
-
-// Filter on availability signals.
-message AvailabilityFilter {
- // Required. Type of signal to apply filter on.
- AvailabilitySignalType signal_type = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. Range of times to filter candidate signals by.
- TimestampRange range = 2 [(google.api.field_behavior) = REQUIRED];
-
- // If multiple [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter] are provided, the default
- // behavior is to OR all filters, but if this field is set to true, this
- // particular [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter] will be AND'ed against other
- // [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter].
- bool required = 3;
-}
-
-// Filter on person name.
-message PersonNameFilter {
- // Required. The person name. For example, "John Smith".
- //
- // Can be any combination of [PersonName.structured_name.given_name][],
- // [PersonName.structured_name.middle_initial][],
- // [PersonName.structured_name.family_name][], and
- // [PersonName.formatted_name][google.cloud.talent.v4beta1.PersonName.formatted_name].
- string person_name = 1 [(google.api.field_behavior) = REQUIRED];
-}
diff --git a/google/cloud/talent_v4beta1/proto/histogram.proto b/google/cloud/talent_v4beta1/proto/histogram.proto
deleted file mode 100644
index 10938690..00000000
--- a/google/cloud/talent_v4beta1/proto/histogram.proto
+++ /dev/null
@@ -1,53 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "HistogramProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// The histogram request.
-message HistogramQuery {
- // An expression specifies a histogram request against matching resources
- // (for example, jobs, profiles) for searches.
- //
- // See [SearchJobsRequest.histogram_queries][google.cloud.talent.v4beta1.SearchJobsRequest.histogram_queries] and
- // [SearchProfilesRequest.histogram_queries][google.cloud.talent.v4beta1.SearchProfilesRequest.histogram_queries] for details about syntax.
- string histogram_query = 1;
-}
-
-// Histogram result that matches [HistogramQuery][google.cloud.talent.v4beta1.HistogramQuery] specified in searches.
-message HistogramQueryResult {
- // Requested histogram expression.
- string histogram_query = 1;
-
- // A map from the values of the facet associated with distinct values to the
- // number of matching entries with corresponding value.
- //
- // The key format is:
- //
- // * (for string histogram) string values stored in the field.
- // * (for named numeric bucket) name specified in `bucket()` function, like
- // for `bucket(0, MAX, "non-negative")`, the key will be `non-negative`.
- // * (for anonymous numeric bucket) range formatted as `-`, for
- // example, `0-1000`, `MIN-0`, and `0-MAX`.
- map histogram = 2;
-}
diff --git a/google/cloud/talent_v4beta1/proto/job.proto b/google/cloud/talent_v4beta1/proto/job.proto
deleted file mode 100644
index b2ffa2bc..00000000
--- a/google/cloud/talent_v4beta1/proto/job.proto
+++ /dev/null
@@ -1,350 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/protobuf/timestamp.proto";
-import "google/type/postal_address.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "JobResourceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A Job resource represents a job posting (also referred to as a "job listing"
-// or "job requisition"). A job belongs to a [Company][google.cloud.talent.v4beta1.Company], which is the hiring
-// entity responsible for the job.
-message Job {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Job"
- pattern: "projects/{project}/tenants/{tenant}/jobs/{job}"
- pattern: "projects/{project}/jobs/{job}"
- };
-
- // Application related details of a job posting.
- message ApplicationInfo {
- // Use this field to specify email address(es) to which resumes or
- // applications can be sent.
- //
- // The maximum number of allowed characters for each entry is 255.
- repeated string emails = 1;
-
- // Use this field to provide instructions, such as "Mail your application
- // to ...", that a candidate can follow to apply for the job.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 3,000.
- string instruction = 2;
-
- // Use this URI field to direct an applicant to a website, for example to
- // link to an online application form.
- //
- // The maximum number of allowed characters for each entry is 2,000.
- repeated string uris = 3;
- }
-
- // Derived details about the job posting.
- message DerivedInfo {
- // Structured locations of the job, resolved from [Job.addresses][google.cloud.talent.v4beta1.Job.addresses].
- //
- // [locations][google.cloud.talent.v4beta1.Job.DerivedInfo.locations] are exactly matched to [Job.addresses][google.cloud.talent.v4beta1.Job.addresses] in the same
- // order.
- repeated Location locations = 1;
-
- // Job categories derived from [Job.title][google.cloud.talent.v4beta1.Job.title] and [Job.description][google.cloud.talent.v4beta1.Job.description].
- repeated JobCategory job_categories = 3;
- }
-
- // Options for job processing.
- message ProcessingOptions {
- // If set to `true`, the service does not attempt to resolve a
- // more precise address for the job.
- bool disable_street_address_resolution = 1;
-
- // Option for job HTML content sanitization. Applied fields are:
- //
- // * description
- // * applicationInfo.instruction
- // * incentives
- // * qualifications
- // * responsibilities
- //
- // HTML tags in these fields may be stripped if sanitiazation isn't
- // disabled.
- //
- // Defaults to [HtmlSanitization.SIMPLE_FORMATTING_ONLY][google.cloud.talent.v4beta1.HtmlSanitization.SIMPLE_FORMATTING_ONLY].
- HtmlSanitization html_sanitization = 2;
- }
-
- // Required during job update.
- //
- // The resource name for the job. This is generated by the service when a
- // job is created.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}". For
- // example, "projects/foo/tenants/bar/jobs/baz".
- //
- // If tenant id is unspecified, the default tenant is used. For
- // example, "projects/foo/jobs/bar".
- //
- // Use of this field in job queries and API calls is preferred over the use of
- // [requisition_id][google.cloud.talent.v4beta1.Job.requisition_id] since this value is unique.
- string name = 1;
-
- // Required. The resource name of the company listing the job.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/companies/{company_id}". For
- // example, "projects/foo/tenants/bar/companies/baz".
- //
- // If tenant id is unspecified, the default tenant is used. For
- // example, "projects/foo/companies/bar".
- string company = 2 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Company"
- }
- ];
-
- // Required. The requisition ID, also referred to as the posting ID, is assigned by the
- // client to identify a job. This field is intended to be used by clients
- // for client identification and tracking of postings. A job isn't allowed
- // to be created if there is another job with the same [company][google.cloud.talent.v4beta1.Job.name],
- // [language_code][google.cloud.talent.v4beta1.Job.language_code] and [requisition_id][google.cloud.talent.v4beta1.Job.requisition_id].
- //
- // The maximum number of allowed characters is 255.
- string requisition_id = 3 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The title of the job, such as "Software Engineer"
- //
- // The maximum number of allowed characters is 500.
- string title = 4 [(google.api.field_behavior) = REQUIRED];
-
- // Required. The description of the job, which typically includes a multi-paragraph
- // description of the company and related information. Separate fields are
- // provided on the job object for [responsibilities][google.cloud.talent.v4beta1.Job.responsibilities],
- // [qualifications][google.cloud.talent.v4beta1.Job.qualifications], and other job characteristics. Use of
- // these separate job fields is recommended.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 100,000.
- string description = 5 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // Location(s) where the employer is looking to hire for this job posting.
- //
- // Specifying the full street address(es) of the hiring location enables
- // better API results, especially job searches by commute time.
- //
- // At most 50 locations are allowed for best search performance. If a job has
- // more locations, it is suggested to split it into multiple jobs with unique
- // [requisition_id][google.cloud.talent.v4beta1.Job.requisition_id]s (e.g. 'ReqA' becomes 'ReqA-1', 'ReqA-2', and so on.) as
- // multiple jobs with the same [company][google.cloud.talent.v4beta1.Job.company], [language_code][google.cloud.talent.v4beta1.Job.language_code] and
- // [requisition_id][google.cloud.talent.v4beta1.Job.requisition_id] are not allowed. If the original [requisition_id][google.cloud.talent.v4beta1.Job.requisition_id] must
- // be preserved, a custom field should be used for storage. It is also
- // suggested to group the locations that close to each other in the same job
- // for better search experience.
- //
- // The maximum number of allowed characters is 500.
- repeated string addresses = 6;
-
- // Job application information.
- ApplicationInfo application_info = 7;
-
- // The benefits included with the job.
- repeated JobBenefit job_benefits = 8;
-
- // Job compensation information (a.k.a. "pay rate") i.e., the compensation
- // that will paid to the employee.
- CompensationInfo compensation_info = 9;
-
- // A map of fields to hold both filterable and non-filterable custom job
- // attributes that are not covered by the provided structured fields.
- //
- // The keys of the map are strings up to 64 bytes and must match the
- // pattern: [a-zA-Z][a-zA-Z0-9_]*. For example, key0LikeThis or
- // KEY_1_LIKE_THIS.
- //
- // At most 100 filterable and at most 100 unfilterable keys are supported.
- // For filterable `string_values`, across all keys at most 200 values are
- // allowed, with each string no more than 255 characters. For unfilterable
- // `string_values`, the maximum total size of `string_values` across all keys
- // is 50KB.
- map custom_attributes = 10;
-
- // The desired education degrees for the job, such as Bachelors, Masters.
- repeated DegreeType degree_types = 11;
-
- // The department or functional area within the company with the open
- // position.
- //
- // The maximum number of allowed characters is 255.
- string department = 12;
-
- // The employment type(s) of a job, for example,
- // [full time][google.cloud.talent.v4beta1.EmploymentType.FULL_TIME] or
- // [part time][google.cloud.talent.v4beta1.EmploymentType.PART_TIME].
- repeated EmploymentType employment_types = 13;
-
- // A description of bonus, commission, and other compensation
- // incentives associated with the job not including salary or pay.
- //
- // The maximum number of allowed characters is 10,000.
- string incentives = 14;
-
- // The language of the posting. This field is distinct from
- // any requirements for fluency that are associated with the job.
- //
- // Language codes must be in BCP-47 format, such as "en-US" or "sr-Latn".
- // For more information, see
- // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47){:
- // class="external" target="_blank" }.
- //
- // If this field is unspecified and [Job.description][google.cloud.talent.v4beta1.Job.description] is present, detected
- // language code based on [Job.description][google.cloud.talent.v4beta1.Job.description] is assigned, otherwise
- // defaults to 'en_US'.
- string language_code = 15;
-
- // The experience level associated with the job, such as "Entry Level".
- JobLevel job_level = 16;
-
- // A promotion value of the job, as determined by the client.
- // The value determines the sort order of the jobs returned when searching for
- // jobs using the featured jobs search call, with higher promotional values
- // being returned first and ties being resolved by relevance sort. Only the
- // jobs with a promotionValue >0 are returned in a FEATURED_JOB_SEARCH.
- //
- // Default value is 0, and negative values are treated as 0.
- int32 promotion_value = 17;
-
- // A description of the qualifications required to perform the
- // job. The use of this field is recommended
- // as an alternative to using the more general [description][google.cloud.talent.v4beta1.Job.description] field.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 10,000.
- string qualifications = 18;
-
- // A description of job responsibilities. The use of this field is
- // recommended as an alternative to using the more general [description][google.cloud.talent.v4beta1.Job.description]
- // field.
- //
- // This field accepts and sanitizes HTML input, and also accepts
- // bold, italic, ordered list, and unordered list markup tags.
- //
- // The maximum number of allowed characters is 10,000.
- string responsibilities = 19;
-
- // The job [PostingRegion][google.cloud.talent.v4beta1.PostingRegion] (for example, state, country) throughout
- // which the job is available. If this field is set, a [LocationFilter][google.cloud.talent.v4beta1.LocationFilter]
- // in a search query within the job region finds this job posting if an
- // exact location match isn't specified. If this field is set to
- // [PostingRegion.NATION][google.cloud.talent.v4beta1.PostingRegion.NATION] or [PostingRegion.ADMINISTRATIVE_AREA][google.cloud.talent.v4beta1.PostingRegion.ADMINISTRATIVE_AREA],
- // setting job [Job.addresses][google.cloud.talent.v4beta1.Job.addresses] to the same location level as this field
- // is strongly recommended.
- PostingRegion posting_region = 20;
-
- // Deprecated. The job is only visible to the owner.
- //
- // The visibility of the job.
- //
- // Defaults to [Visibility.ACCOUNT_ONLY][google.cloud.talent.v4beta1.Visibility.ACCOUNT_ONLY] if not specified.
- Visibility visibility = 21 [deprecated = true];
-
- // The start timestamp of the job in UTC time zone. Typically this field
- // is used for contracting engagements. Invalid timestamps are ignored.
- google.protobuf.Timestamp job_start_time = 22;
-
- // The end timestamp of the job. Typically this field is used for contracting
- // engagements. Invalid timestamps are ignored.
- google.protobuf.Timestamp job_end_time = 23;
-
- // The timestamp this job posting was most recently published. The default
- // value is the time the request arrives at the server. Invalid timestamps are
- // ignored.
- google.protobuf.Timestamp posting_publish_time = 24;
-
- // Strongly recommended for the best service experience.
- //
- // The expiration timestamp of the job. After this timestamp, the
- // job is marked as expired, and it no longer appears in search results. The
- // expired job can't be listed by the [ListJobs][google.cloud.talent.v4beta1.JobService.ListJobs] API,
- // but it can be retrieved with the [GetJob][google.cloud.talent.v4beta1.JobService.GetJob] API or
- // updated with the [UpdateJob][google.cloud.talent.v4beta1.JobService.UpdateJob] API or deleted with
- // the [DeleteJob][google.cloud.talent.v4beta1.JobService.DeleteJob] API. An expired job can
- // be updated and opened again by using a future expiration timestamp.
- // Updating an expired job fails if there is another existing open job with
- // same [company][google.cloud.talent.v4beta1.Job.company], [language_code][google.cloud.talent.v4beta1.Job.language_code] and [requisition_id][google.cloud.talent.v4beta1.Job.requisition_id].
- //
- // The expired jobs are retained in our system for 90 days. However, the
- // overall expired job count cannot exceed 3 times the maximum number of
- // open jobs over previous 7 days. If this threshold is exceeded,
- // expired jobs are cleaned out in order of earliest expire time.
- // Expired jobs are no longer accessible after they are cleaned
- // out.
- //
- // Invalid timestamps are ignored, and treated as expire time not provided.
- //
- // If the timestamp is before the instant request is made, the job
- // is treated as expired immediately on creation. This kind of job can
- // not be updated. And when creating a job with past timestamp, the
- // [posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] must be set before
- // [posting_expire_time][google.cloud.talent.v4beta1.Job.posting_expire_time]. The purpose of this feature is
- // to allow other objects, such as [Application][google.cloud.talent.v4beta1.Application], to refer a job
- // that didn't exist in the system prior to becoming expired. If you
- // want to modify a job that was expired on creation,
- // delete it and create a new one.
- //
- // If this value isn't provided at the time of job creation or is invalid,
- // the job posting expires after 30 days from the job's creation time. For
- // example, if the job was created on 2017/01/01 13:00AM UTC with an
- // unspecified expiration date, the job expires after 2017/01/31 13:00AM UTC.
- //
- // If this value isn't provided on job update, it depends on the field masks
- // set by [UpdateJobRequest.update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask]. If the field masks include
- // [job_end_time][google.cloud.talent.v4beta1.Job.job_end_time], or the masks are empty meaning that every field is
- // updated, the job posting expires after 30 days from the job's last
- // update time. Otherwise the expiration date isn't updated.
- google.protobuf.Timestamp posting_expire_time = 25;
-
- // Output only. The timestamp when this job posting was created.
- google.protobuf.Timestamp posting_create_time = 26 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. The timestamp when this job posting was last updated.
- google.protobuf.Timestamp posting_update_time = 27 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Display name of the company listing the job.
- string company_display_name = 28 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Derived details about the job posting.
- DerivedInfo derived_info = 29 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Options for job processing.
- ProcessingOptions processing_options = 30;
-}
diff --git a/google/cloud/talent_v4beta1/proto/job_service.proto b/google/cloud/talent_v4beta1/proto/job_service.proto
deleted file mode 100644
index 148e6486..00000000
--- a/google/cloud/talent_v4beta1/proto/job_service.proto
+++ /dev/null
@@ -1,910 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/cloud/talent/v4beta1/filters.proto";
-import "google/cloud/talent/v4beta1/histogram.proto";
-import "google/cloud/talent/v4beta1/job.proto";
-import "google/longrunning/operations.proto";
-import "google/protobuf/any.proto";
-import "google/protobuf/duration.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-import "google/rpc/status.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "JobServiceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A service handles job management, including job CRUD, enumeration and search.
-service JobService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Creates a new job.
- //
- // Typically, the job becomes searchable within 10 seconds, but it may take
- // up to 5 minutes.
- rpc CreateJob(CreateJobRequest) returns (Job) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/jobs"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/jobs"
- body: "*"
- }
- };
- option (google.api.method_signature) = "parent,job";
- }
-
- // Begins executing a batch create jobs operation.
- rpc BatchCreateJobs(BatchCreateJobsRequest) returns (google.longrunning.Operation) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/jobs:batchCreate"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/jobs:batchCreate"
- body: "*"
- }
- };
- option (google.api.method_signature) = "parent,jobs";
- option (google.longrunning.operation_info) = {
- response_type: "JobOperationResult"
- metadata_type: "BatchOperationMetadata"
- };
- }
-
- // Retrieves the specified job, whose status is OPEN or recently EXPIRED
- // within the last 90 days.
- rpc GetJob(GetJobRequest) returns (Job) {
- option (google.api.http) = {
- get: "/v4beta1/{name=projects/*/tenants/*/jobs/*}"
- additional_bindings {
- get: "/v4beta1/{name=projects/*/jobs/*}"
- }
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates specified job.
- //
- // Typically, updated contents become visible in search results within 10
- // seconds, but it may take up to 5 minutes.
- rpc UpdateJob(UpdateJobRequest) returns (Job) {
- option (google.api.http) = {
- patch: "/v4beta1/{job.name=projects/*/tenants/*/jobs/*}"
- body: "*"
- additional_bindings {
- patch: "/v4beta1/{job.name=projects/*/jobs/*}"
- body: "*"
- }
- };
- option (google.api.method_signature) = "job";
- }
-
- // Begins executing a batch update jobs operation.
- rpc BatchUpdateJobs(BatchUpdateJobsRequest) returns (google.longrunning.Operation) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/jobs:batchUpdate"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/jobs:batchUpdate"
- body: "*"
- }
- };
- option (google.api.method_signature) = "parent,jobs";
- option (google.longrunning.operation_info) = {
- response_type: "JobOperationResult"
- metadata_type: "BatchOperationMetadata"
- };
- }
-
- // Deletes the specified job.
- //
- // Typically, the job becomes unsearchable within 10 seconds, but it may take
- // up to 5 minutes.
- rpc DeleteJob(DeleteJobRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4beta1/{name=projects/*/tenants/*/jobs/*}"
- additional_bindings {
- delete: "/v4beta1/{name=projects/*/jobs/*}"
- }
- };
- option (google.api.method_signature) = "name";
- }
-
- // Deletes a list of [Job][google.cloud.talent.v4beta1.Job]s by filter.
- rpc BatchDeleteJobs(BatchDeleteJobsRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/jobs:batchDelete"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/jobs:batchDelete"
- }
- };
- option (google.api.method_signature) = "parent,filter";
- }
-
- // Lists jobs by filter.
- rpc ListJobs(ListJobsRequest) returns (ListJobsResponse) {
- option (google.api.http) = {
- get: "/v4beta1/{parent=projects/*/tenants/*}/jobs"
- additional_bindings {
- get: "/v4beta1/{parent=projects/*}/jobs"
- }
- };
- option (google.api.method_signature) = "parent,filter";
- }
-
- // Searches for jobs using the provided [SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
- //
- // This call constrains the [visibility][google.cloud.talent.v4beta1.Job.visibility] of jobs
- // present in the database, and only returns jobs that the caller has
- // permission to search against.
- rpc SearchJobs(SearchJobsRequest) returns (SearchJobsResponse) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/jobs:search"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/jobs:search"
- body: "*"
- }
- };
- }
-
- // Searches for jobs using the provided [SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
- //
- // This API call is intended for the use case of targeting passive job
- // seekers (for example, job seekers who have signed up to receive email
- // alerts about potential job opportunities), and has different algorithmic
- // adjustments that are targeted to passive job seekers.
- //
- // This call constrains the [visibility][google.cloud.talent.v4beta1.Job.visibility] of jobs
- // present in the database, and only returns jobs the caller has
- // permission to search against.
- rpc SearchJobsForAlert(SearchJobsRequest) returns (SearchJobsResponse) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/jobs:searchForAlert"
- body: "*"
- additional_bindings {
- post: "/v4beta1/{parent=projects/*}/jobs:searchForAlert"
- body: "*"
- }
- };
- }
-}
-
-// Create job request.
-message CreateJobRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenant/bar". If tenant id is unspecified a default tenant
- // is created. For example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The Job to be created.
- Job job = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Get job request.
-message GetJobRequest {
- // Required. The resource name of the job to retrieve.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}". For
- // example, "projects/foo/tenants/bar/jobs/baz".
- //
- // If tenant id is unspecified, the default tenant is used. For
- // example, "projects/foo/jobs/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Job"
- }
- ];
-}
-
-// Update job request.
-message UpdateJobRequest {
- // Required. The Job to be updated.
- Job job = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // If [update_mask][google.cloud.talent.v4beta1.UpdateJobRequest.update_mask] is provided, only the specified fields in
- // [job][google.cloud.talent.v4beta1.UpdateJobRequest.job] are updated. Otherwise all the fields are updated.
- //
- // A field mask to restrict the fields that are updated. Only
- // top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Delete job request.
-message DeleteJobRequest {
- // Required. The resource name of the job to be deleted.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}". For
- // example, "projects/foo/tenants/bar/jobs/baz".
- //
- // If tenant id is unspecified, the default tenant is used. For
- // example, "projects/foo/jobs/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Job"
- }
- ];
-}
-
-// Batch delete jobs request.
-message BatchDeleteJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
- // is created. For example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The filter string specifies the jobs to be deleted.
- //
- // Supported operator: =, AND
- //
- // The fields eligible for filtering are:
- //
- // * `companyName` (Required)
- // * `requisitionId` (Required)
- //
- // Sample Query: companyName = "projects/foo/companies/bar" AND
- // requisitionId = "req-1"
- string filter = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// List jobs request.
-message ListJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
- // is created. For example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The filter string specifies the jobs to be enumerated.
- //
- // Supported operator: =, AND
- //
- // The fields eligible for filtering are:
- //
- // * `companyName` (Required)
- // * `requisitionId`
- // * `status` Available values: OPEN, EXPIRED, ALL. Defaults to
- // OPEN if no value is specified.
- //
- // Sample Query:
- //
- // * companyName = "projects/foo/tenants/bar/companies/baz"
- // * companyName = "projects/foo/tenants/bar/companies/baz" AND
- // requisitionId = "req-1"
- // * companyName = "projects/foo/tenants/bar/companies/baz" AND
- // status = "EXPIRED"
- string filter = 2 [(google.api.field_behavior) = REQUIRED];
-
- // The starting point of a query result.
- string page_token = 3;
-
- // The maximum number of jobs to be returned per page of results.
- //
- // If [job_view][google.cloud.talent.v4beta1.ListJobsRequest.job_view] is set to [JobView.JOB_VIEW_ID_ONLY][google.cloud.talent.v4beta1.JobView.JOB_VIEW_ID_ONLY], the maximum allowed
- // page size is 1000. Otherwise, the maximum allowed page size is 100.
- //
- // Default is 100 if empty or a number < 1 is specified.
- int32 page_size = 4;
-
- // The desired job attributes returned for jobs in the
- // search response. Defaults to [JobView.JOB_VIEW_FULL][google.cloud.talent.v4beta1.JobView.JOB_VIEW_FULL] if no value is
- // specified.
- JobView job_view = 5;
-}
-
-// An enum that specifies the job attributes that are returned in the
-// [MatchingJob.job][google.cloud.talent.v4beta1.SearchJobsResponse.MatchingJob.job] or
-// [ListJobsResponse.jobs][google.cloud.talent.v4beta1.ListJobsResponse.jobs] fields.
-enum JobView {
- // Default value.
- JOB_VIEW_UNSPECIFIED = 0;
-
- // A ID only view of job, with following attributes:
- // [Job.name][google.cloud.talent.v4beta1.Job.name], [Job.requisition_id][google.cloud.talent.v4beta1.Job.requisition_id], [Job.language_code][google.cloud.talent.v4beta1.Job.language_code].
- JOB_VIEW_ID_ONLY = 1;
-
- // A minimal view of the job, with the following attributes:
- // [Job.name][google.cloud.talent.v4beta1.Job.name], [Job.requisition_id][google.cloud.talent.v4beta1.Job.requisition_id], [Job.title][google.cloud.talent.v4beta1.Job.title],
- // [Job.company][google.cloud.talent.v4beta1.Job.company], [Job.DerivedInfo.locations][google.cloud.talent.v4beta1.Job.DerivedInfo.locations], [Job.language_code][google.cloud.talent.v4beta1.Job.language_code].
- JOB_VIEW_MINIMAL = 2;
-
- // A small view of the job, with the following attributes in the search
- // results: [Job.name][google.cloud.talent.v4beta1.Job.name], [Job.requisition_id][google.cloud.talent.v4beta1.Job.requisition_id], [Job.title][google.cloud.talent.v4beta1.Job.title],
- // [Job.company][google.cloud.talent.v4beta1.Job.company], [Job.DerivedInfo.locations][google.cloud.talent.v4beta1.Job.DerivedInfo.locations], [Job.visibility][google.cloud.talent.v4beta1.Job.visibility],
- // [Job.language_code][google.cloud.talent.v4beta1.Job.language_code], [Job.description][google.cloud.talent.v4beta1.Job.description].
- JOB_VIEW_SMALL = 3;
-
- // All available attributes are included in the search results.
- JOB_VIEW_FULL = 4;
-}
-
-// List jobs response.
-message ListJobsResponse {
- // The Jobs for a given company.
- //
- // The maximum number of items returned is based on the limit field
- // provided in the request.
- repeated Job jobs = 1;
-
- // A token to retrieve the next page of results.
- string next_page_token = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-}
-
-// The Request body of the `SearchJobs` call.
-message SearchJobsRequest {
- // Custom ranking information for [SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
- message CustomRankingInfo {
- // The importance level for [CustomRankingInfo.ranking_expression][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.ranking_expression].
- enum ImportanceLevel {
- // Default value if the importance level isn't specified.
- IMPORTANCE_LEVEL_UNSPECIFIED = 0;
-
- // The given ranking expression is of None importance, existing relevance
- // score (determined by API algorithm) dominates job's final ranking
- // position.
- NONE = 1;
-
- // The given ranking expression is of Low importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- LOW = 2;
-
- // The given ranking expression is of Mild importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- MILD = 3;
-
- // The given ranking expression is of Medium importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- MEDIUM = 4;
-
- // The given ranking expression is of High importance in terms of job's
- // final ranking position compared to existing relevance
- // score (determined by API algorithm).
- HIGH = 5;
-
- // The given ranking expression is of Extreme importance, and dominates
- // job's final ranking position with existing relevance
- // score (determined by API algorithm) ignored.
- EXTREME = 6;
- }
-
- // Required. Controls over how important the score of
- // [CustomRankingInfo.ranking_expression][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.ranking_expression] gets applied to job's final
- // ranking position.
- //
- // An error is thrown if not specified.
- ImportanceLevel importance_level = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Required. Controls over how job documents get ranked on top of existing relevance
- // score (determined by API algorithm). A combination of the ranking
- // expression and relevance score is used to determine job's final ranking
- // position.
- //
- // The syntax for this expression is a subset of Google SQL syntax.
- //
- // Supported operators are: +, -, *, /, where the left and right side of
- // the operator is either a numeric [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes] key,
- // integer/double value or an expression that can be evaluated to a number.
- //
- // Parenthesis are supported to adjust calculation precedence. The
- // expression must be < 100 characters in length.
- //
- // The expression is considered invalid for a job if the expression
- // references custom attributes that are not populated on the job or if the
- // expression results in a divide by zero. If an expression is invalid for a
- // job, that job is demoted to the end of the results.
- //
- // Sample ranking expression
- // (year + 25) * 0.25 - (freshness / 0.5)
- string ranking_expression = 2 [(google.api.field_behavior) = REQUIRED];
- }
-
- // A string-represented enumeration of the job search mode. The service
- // operate differently for different modes of service.
- enum SearchMode {
- // The mode of the search method isn't specified. The default search
- // behavior is identical to JOB_SEARCH search behavior.
- SEARCH_MODE_UNSPECIFIED = 0;
-
- // The job search matches against all jobs, and featured jobs
- // (jobs with promotionValue > 0) are not specially handled.
- JOB_SEARCH = 1;
-
- // The job search matches only against featured jobs (jobs with a
- // promotionValue > 0). This method doesn't return any jobs having a
- // promotionValue <= 0. The search results order is determined by the
- // promotionValue (jobs with a higher promotionValue are returned higher up
- // in the search results), with relevance being used as a tiebreaker.
- FEATURED_JOB_SEARCH = 2;
- }
-
- // Controls whether highly similar jobs are returned next to each other in
- // the search results. Jobs are identified as highly similar based on
- // their titles, job categories, and locations. Highly similar results are
- // clustered so that only one representative job of the cluster is
- // displayed to the job seeker higher up in the results, with the other jobs
- // being displayed lower down in the results.
- enum DiversificationLevel {
- // The diversification level isn't specified.
- DIVERSIFICATION_LEVEL_UNSPECIFIED = 0;
-
- // Disables diversification. Jobs that would normally be pushed to the last
- // page would not have their positions altered. This may result in highly
- // similar jobs appearing in sequence in the search results.
- DISABLED = 1;
-
- // Default diversifying behavior. The result list is ordered so that
- // highly similar results are pushed to the end of the last page of search
- // results. If you are using pageToken to page through the result set,
- // latency might be lower but we can't guarantee that all results are
- // returned. If you are using page offset, latency might be higher but all
- // results are returned.
- SIMPLE = 2;
- }
-
- // Required. The resource name of the tenant to search within.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
- // is created. For example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Mode of a search.
- //
- // Defaults to [SearchMode.JOB_SEARCH][google.cloud.talent.v4beta1.SearchJobsRequest.SearchMode.JOB_SEARCH].
- SearchMode search_mode = 2;
-
- // Required. The meta information collected about the job searcher, used to improve the
- // search quality of the service. The identifiers (such as `user_id`) are
- // provided by users, and must be unique and consistent.
- RequestMetadata request_metadata = 3 [(google.api.field_behavior) = REQUIRED];
-
- // Query used to search against jobs, such as keyword, location filters, etc.
- JobQuery job_query = 4;
-
- // Controls whether to broaden the search when it produces sparse results.
- // Broadened queries append results to the end of the matching results
- // list.
- //
- // Defaults to false.
- bool enable_broadening = 5;
-
- // Controls if the search job request requires the return of a precise
- // count of the first 300 results. Setting this to `true` ensures
- // consistency in the number of results per page. Best practice is to set this
- // value to true if a client allows users to jump directly to a
- // non-sequential search results page.
- //
- // Enabling this flag may adversely impact performance.
- //
- // Defaults to false.
- bool require_precise_result_size = 6;
-
- // An expression specifies a histogram request against matching jobs.
- //
- // Expression syntax is an aggregation function call with histogram facets and
- // other options.
- //
- // Available aggregation function calls are:
- // * `count(string_histogram_facet)`: Count the number of matching entities,
- // for each distinct attribute value.
- // * `count(numeric_histogram_facet, list of buckets)`: Count the number of
- // matching entities within each bucket.
- //
- // Data types:
- //
- // * Histogram facet: facet names with format [a-zA-Z][a-zA-Z0-9_]+.
- // * String: string like "any string with backslash escape for quote(\")."
- // * Number: whole number and floating point number like 10, -1 and -0.01.
- // * List: list of elements with comma(,) separator surrounded by square
- // brackets, for example, [1, 2, 3] and ["one", "two", "three"].
- //
- // Built-in constants:
- //
- // * MIN (minimum number similar to java Double.MIN_VALUE)
- // * MAX (maximum number similar to java Double.MAX_VALUE)
- //
- // Built-in functions:
- //
- // * bucket(start, end[, label]): bucket built-in function creates a bucket
- // with range of [start, end). Note that the end is exclusive, for example,
- // bucket(1, MAX, "positive number") or bucket(1, 10).
- //
- // Job histogram facets:
- //
- // * company_display_name: histogram by [Job.company_display_name][google.cloud.talent.v4beta1.Job.company_display_name].
- // * employment_type: histogram by [Job.employment_types][google.cloud.talent.v4beta1.Job.employment_types], for example,
- // "FULL_TIME", "PART_TIME".
- // * company_size: histogram by [CompanySize][google.cloud.talent.v4beta1.CompanySize], for example, "SMALL",
- // "MEDIUM", "BIG".
- // * publish_time_in_month: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time]
- // in months.
- // Must specify list of numeric buckets in spec.
- // * publish_time_in_year: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time]
- // in years.
- // Must specify list of numeric buckets in spec.
- // * degree_types: histogram by the [Job.degree_types][google.cloud.talent.v4beta1.Job.degree_types], for example,
- // "Bachelors", "Masters".
- // * job_level: histogram by the [Job.job_level][google.cloud.talent.v4beta1.Job.job_level], for example, "Entry
- // Level".
- // * country: histogram by the country code of jobs, for example, "US", "FR".
- // * admin1: histogram by the admin1 code of jobs, which is a global
- // placeholder referring to the state, province, or the particular term a
- // country uses to define the geographic structure below the country level,
- // for example, "CA", "IL".
- // * city: histogram by a combination of the "city name, admin1 code". For
- // example, "Mountain View, CA", "New York, NY".
- // * admin1_country: histogram by a combination of the "admin1 code, country",
- // for example, "CA, US", "IL, US".
- // * city_coordinate: histogram by the city center's GPS coordinates (latitude
- // and longitude), for example, 37.4038522,-122.0987765. Since the
- // coordinates of a city center can change, customers may need to refresh
- // them periodically.
- // * locale: histogram by the [Job.language_code][google.cloud.talent.v4beta1.Job.language_code], for example, "en-US",
- // "fr-FR".
- // * language: histogram by the language subtag of the [Job.language_code][google.cloud.talent.v4beta1.Job.language_code],
- // for example, "en", "fr".
- // * category: histogram by the [JobCategory][google.cloud.talent.v4beta1.JobCategory], for example,
- // "COMPUTER_AND_IT", "HEALTHCARE".
- // * base_compensation_unit: histogram by the
- // [CompensationInfo.CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit] of base
- // salary, for example, "WEEKLY", "MONTHLY".
- // * base_compensation: histogram by the base salary. Must specify list of
- // numeric buckets to group results by.
- // * annualized_base_compensation: histogram by the base annualized salary.
- // Must specify list of numeric buckets to group results by.
- // * annualized_total_compensation: histogram by the total annualized salary.
- // Must specify list of numeric buckets to group results by.
- // * string_custom_attribute: histogram by string [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes].
- // Values can be accessed via square bracket notations like
- // string_custom_attribute["key1"].
- // * numeric_custom_attribute: histogram by numeric [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes].
- // Values can be accessed via square bracket notations like
- // numeric_custom_attribute["key1"]. Must specify list of numeric buckets to
- // group results by.
- //
- // Example expressions:
- //
- // * `count(admin1)`
- // * `count(base_compensation, [bucket(1000, 10000), bucket(10000, 100000),
- // bucket(100000, MAX)])`
- // * `count(string_custom_attribute["some-string-custom-attribute"])`
- // * `count(numeric_custom_attribute["some-numeric-custom-attribute"],
- // [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative"])`
- repeated HistogramQuery histogram_queries = 7;
-
- // The desired job attributes returned for jobs in the search response.
- // Defaults to [JobView.JOB_VIEW_SMALL][google.cloud.talent.v4beta1.JobView.JOB_VIEW_SMALL] if no value is specified.
- JobView job_view = 8;
-
- // An integer that specifies the current offset (that is, starting result
- // location, amongst the jobs deemed by the API as relevant) in search
- // results. This field is only considered if [page_token][google.cloud.talent.v4beta1.SearchJobsRequest.page_token] is unset.
- //
- // The maximum allowed value is 5000. Otherwise an error is thrown.
- //
- // For example, 0 means to return results starting from the first matching
- // job, and 10 means to return from the 11th job. This can be used for
- // pagination, (for example, pageSize = 10 and offset = 10 means to return
- // from the second page).
- int32 offset = 9;
-
- // A limit on the number of jobs returned in the search results.
- // Increasing this value above the default value of 10 can increase search
- // response time. The value can be between 1 and 100.
- int32 page_size = 10;
-
- // The token specifying the current offset within
- // search results. See [SearchJobsResponse.next_page_token][google.cloud.talent.v4beta1.SearchJobsResponse.next_page_token] for
- // an explanation of how to obtain the next set of query results.
- string page_token = 11;
-
- // The criteria determining how search results are sorted. Default is
- // `"relevance desc"`.
- //
- // Supported options are:
- //
- // * `"relevance desc"`: By relevance descending, as determined by the API
- // algorithms. Relevance thresholding of query results is only available
- // with this ordering.
- // * `"posting_publish_time desc"`: By [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time]
- // descending.
- // * `"posting_update_time desc"`: By [Job.posting_update_time][google.cloud.talent.v4beta1.Job.posting_update_time]
- // descending.
- // * `"title"`: By [Job.title][google.cloud.talent.v4beta1.Job.title] ascending.
- // * `"title desc"`: By [Job.title][google.cloud.talent.v4beta1.Job.title] descending.
- // * `"annualized_base_compensation"`: By job's
- // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_base_compensation_range] ascending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"annualized_base_compensation desc"`: By job's
- // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_base_compensation_range] descending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"annualized_total_compensation"`: By job's
- // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_total_compensation_range] ascending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"annualized_total_compensation desc"`: By job's
- // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_total_compensation_range] descending. Jobs
- // whose annualized base compensation is unspecified are put at the end of
- // search results.
- // * `"custom_ranking desc"`: By the relevance score adjusted to the
- // [SearchJobsRequest.CustomRankingInfo.ranking_expression][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.ranking_expression] with weight
- // factor assigned by
- // [SearchJobsRequest.CustomRankingInfo.importance_level][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.importance_level] in descending
- // order.
- // * Location sorting: Use the special syntax to order jobs by distance:
- // `"distance_from('Hawaii')"`: Order by distance from Hawaii.
- // `"distance_from(19.89, 155.5)"`: Order by distance from a coordinate.
- // `"distance_from('Hawaii'), distance_from('Puerto Rico')"`: Order by
- // multiple locations. See details below.
- // `"distance_from('Hawaii'), distance_from(19.89, 155.5)"`: Order by
- // multiple locations. See details below.
- // The string can have a maximum of 256 characters. When multiple distance
- // centers are provided, a job that is close to any of the distance centers
- // would have a high rank. When a job has multiple locations, the job
- // location closest to one of the distance centers will be used. Jobs that
- // don't have locations will be ranked at the bottom. Distance is calculated
- // with a precision of 11.3 meters (37.4 feet). Diversification strategy is
- // still applied unless explicitly disabled in
- // [diversification_level][google.cloud.talent.v4beta1.SearchJobsRequest.diversification_level].
- string order_by = 12;
-
- // Controls whether highly similar jobs are returned next to each other in
- // the search results. Jobs are identified as highly similar based on
- // their titles, job categories, and locations. Highly similar results are
- // clustered so that only one representative job of the cluster is
- // displayed to the job seeker higher up in the results, with the other jobs
- // being displayed lower down in the results.
- //
- // Defaults to [DiversificationLevel.SIMPLE][google.cloud.talent.v4beta1.SearchJobsRequest.DiversificationLevel.SIMPLE] if no value
- // is specified.
- DiversificationLevel diversification_level = 13;
-
- // Controls over how job documents get ranked on top of existing relevance
- // score (determined by API algorithm).
- CustomRankingInfo custom_ranking_info = 14;
-
- // Controls whether to disable exact keyword match on [Job.title][google.cloud.talent.v4beta1.Job.title],
- // [Job.description][google.cloud.talent.v4beta1.Job.description], [Job.company_display_name][google.cloud.talent.v4beta1.Job.company_display_name], [Job.addresses][google.cloud.talent.v4beta1.Job.addresses],
- // [Job.qualifications][google.cloud.talent.v4beta1.Job.qualifications]. When disable keyword match is turned off, a
- // keyword match returns jobs that do not match given category filters when
- // there are matching keywords. For example, for the query "program manager,"
- // a result is returned even if the job posting has the title "software
- // developer," which doesn't fall into "program manager" ontology, but does
- // have "program manager" appearing in its description.
- //
- // For queries like "cloud" that don't contain title or
- // location specific ontology, jobs with "cloud" keyword matches are returned
- // regardless of this flag's value.
- //
- // Use [Company.keyword_searchable_job_custom_attributes][google.cloud.talent.v4beta1.Company.keyword_searchable_job_custom_attributes] if
- // company-specific globally matched custom field/attribute string values are
- // needed. Enabling keyword match improves recall of subsequent search
- // requests.
- //
- // Defaults to false.
- bool disable_keyword_match = 16;
-}
-
-// Response for SearchJob method.
-message SearchJobsResponse {
- // Job entry with metadata inside [SearchJobsResponse][google.cloud.talent.v4beta1.SearchJobsResponse].
- message MatchingJob {
- // Job resource that matches the specified [SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
- Job job = 1;
-
- // A summary of the job with core information that's displayed on the search
- // results listing page.
- string job_summary = 2;
-
- // Contains snippets of text from the [Job.title][google.cloud.talent.v4beta1.Job.title] field most
- // closely matching a search query's keywords, if available. The matching
- // query keywords are enclosed in HTML bold tags.
- string job_title_snippet = 3;
-
- // Contains snippets of text from the [Job.description][google.cloud.talent.v4beta1.Job.description] and similar
- // fields that most closely match a search query's keywords, if available.
- // All HTML tags in the original fields are stripped when returned in this
- // field, and matching query keywords are enclosed in HTML bold tags.
- string search_text_snippet = 4;
-
- // Commute information which is generated based on specified
- // [CommuteFilter][google.cloud.talent.v4beta1.CommuteFilter].
- CommuteInfo commute_info = 5;
- }
-
- // Commute details related to this job.
- message CommuteInfo {
- // Location used as the destination in the commute calculation.
- Location job_location = 1;
-
- // The number of seconds required to travel to the job location from the
- // query location. A duration of 0 seconds indicates that the job isn't
- // reachable within the requested duration, but was returned as part of an
- // expanded query.
- google.protobuf.Duration travel_duration = 2;
- }
-
- // The Job entities that match the specified [SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
- repeated MatchingJob matching_jobs = 1;
-
- // The histogram results that match with specified
- // [SearchJobsRequest.histogram_queries][google.cloud.talent.v4beta1.SearchJobsRequest.histogram_queries].
- repeated HistogramQueryResult histogram_query_results = 2;
-
- // The token that specifies the starting position of the next page of results.
- // This field is empty if there are no more results.
- string next_page_token = 3;
-
- // The location filters that the service applied to the specified query. If
- // any filters are lat-lng based, the [Location.location_type][google.cloud.talent.v4beta1.Location.location_type] is
- // [Location.LocationType.LOCATION_TYPE_UNSPECIFIED][google.cloud.talent.v4beta1.Location.LocationType.LOCATION_TYPE_UNSPECIFIED].
- repeated Location location_filters = 4;
-
- // An estimation of the number of jobs that match the specified query.
- //
- // This number isn't guaranteed to be accurate. For accurate results,
- // see [SearchJobsRequest.require_precise_result_size][google.cloud.talent.v4beta1.SearchJobsRequest.require_precise_result_size].
- int32 estimated_total_size = 5;
-
- // The precise result count, which is available only if the client set
- // [SearchJobsRequest.require_precise_result_size][google.cloud.talent.v4beta1.SearchJobsRequest.require_precise_result_size] to `true`, or if the
- // response is the last page of results. Otherwise, the value is `-1`.
- int32 total_size = 6;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 7;
-
- // If query broadening is enabled, we may append additional results from the
- // broadened query. This number indicates how many of the jobs returned in the
- // jobs field are from the broadened query. These results are always at the
- // end of the jobs list. In particular, a value of 0, or if the field isn't
- // set, all the jobs in the jobs list are from the original
- // (without broadening) query. If this field is non-zero, subsequent requests
- // with offset after this result set should contain all broadened results.
- int32 broadened_query_jobs_count = 8;
-
- // The spell checking result, and correction.
- SpellingCorrection spell_correction = 9;
-}
-
-// Request to create a batch of jobs.
-message BatchCreateJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
- // is created. For example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The jobs to be created.
- repeated Job jobs = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Request to update a batch of jobs.
-message BatchUpdateJobsRequest {
- // Required. The resource name of the tenant under which the job is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenant/bar". If tenant id is unspecified, a default tenant
- // is created. For example, "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Job"
- }
- ];
-
- // Required. The jobs to be updated.
- repeated Job jobs = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience. Be aware that it will
- // also increase latency when checking the status of a batch operation.
- //
- // If [update_mask][google.cloud.talent.v4beta1.BatchUpdateJobsRequest.update_mask] is provided, only the specified fields in
- // [Job][google.cloud.talent.v4beta1.Job] are updated. Otherwise all the fields are updated.
- //
- // A field mask to restrict the fields that are updated. Only
- // top level fields of [Job][google.cloud.talent.v4beta1.Job] are supported.
- //
- // If [update_mask][google.cloud.talent.v4beta1.BatchUpdateJobsRequest.update_mask] is provided, The [Job][google.cloud.talent.v4beta1.Job] inside
- // [JobResult][google.cloud.talent.v4beta1.JobOperationResult.JobResult]
- // will only contains fields that is updated, plus the Id of the Job.
- // Otherwise, [Job][google.cloud.talent.v4beta1.Job] will include all fields, which can yield a very
- // large response.
- google.protobuf.FieldMask update_mask = 3;
-}
-
-// The result of [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs] or
-// [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs] APIs. It's used to
-// replace [google.longrunning.Operation.response][google.longrunning.Operation.response] in case of success.
-message JobOperationResult {
- // Mutation result of a job.
- message JobResult {
- // Here [Job][google.cloud.talent.v4beta1.Job] only contains basic information including [name][google.cloud.talent.v4beta1.Job.name],
- // [company][google.cloud.talent.v4beta1.Job.company], [language_code][google.cloud.talent.v4beta1.Job.language_code]
- // and [requisition_id][google.cloud.talent.v4beta1.Job.requisition_id], use getJob method to retrieve
- // detailed information of the created/updated job.
- Job job = 1;
-
- // The status of the job processed. This field is populated if the
- // processing of the [job][google.cloud.talent.v4beta1.JobOperationResult.JobResult.job] fails.
- google.rpc.Status status = 2;
- }
-
- // List of job mutation results from a batch mutate operation. It can change
- // until operation status is FINISHED, FAILED or CANCELLED.
- repeated JobResult job_results = 1;
-}
diff --git a/google/cloud/talent_v4beta1/proto/profile.proto b/google/cloud/talent_v4beta1/proto/profile.proto
deleted file mode 100644
index e087a8cd..00000000
--- a/google/cloud/talent_v4beta1/proto/profile.proto
+++ /dev/null
@@ -1,783 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/protobuf/duration.proto";
-import "google/protobuf/timestamp.proto";
-import "google/protobuf/wrappers.proto";
-import "google/type/date.proto";
-import "google/type/postal_address.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "ProfileResourceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// Cloud Profile Discovery API definition
-
-// A resource that represents the profile for a job candidate (also referred to
-// as a "single-source profile").
-message Profile {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Profile"
- pattern: "projects/{project}/tenants/{tenant}/profiles/{profile}"
- };
-
- // Required during profile update.
- //
- // Resource name assigned to a profile by the API.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}",
- // for example, "projects/foo/tenants/bar/profiles/baz".
- string name = 1;
-
- // Profile's id in client system, if available. This value is unique for each
- // profile inside a tenant. An error is thrown if another profile with the
- // same external_id is created.
- //
- // The maximum number of bytes allowed is 100.
- string external_id = 2;
-
- // The source description indicating where the profile is acquired.
- //
- // For example, if a candidate profile is acquired from a resume, the user can
- // input "resume" here to indicate the source.
- //
- // The maximum number of bytes allowed is 100.
- string source = 3;
-
- // The URI set by clients that links to this profile's client-side copy.
- //
- // The maximum number of bytes allowed is 4000.
- string uri = 4;
-
- // The cluster id of the profile to associate with other profile(s) for the
- // same candidate.
- //
- // This field should be generated by the customer. If a value is not provided,
- // a random UUID is assigned to this field of the profile.
- //
- // This is used to link multiple profiles to the same candidate. For example,
- // a client has a candidate with two profiles, where one was created recently
- // and the other one was created 5 years ago. These two profiles may be very
- // different. The clients can create the first profile and get a generated
- // [group_id][google.cloud.talent.v4beta1.Profile.group_id], and assign it when the second profile is created,
- // indicating these two profiles are referring to the same candidate.
- string group_id = 5;
-
- // Indicates the hirable status of the candidate.
- google.protobuf.BoolValue is_hirable = 6;
-
- // The timestamp when the profile was first created at this source.
- google.protobuf.Timestamp create_time = 7;
-
- // The timestamp when the profile was last updated at this source.
- google.protobuf.Timestamp update_time = 8;
-
- // The timestamp when the profile was last updated as a result of a direct or
- // indirect action by a candidate.
- //
- // These actions include:
- //
- // * Direct actions such as the candidate submitting a new resume as part of a
- // job application to the agency, using a self-service tool such as a website
- // to update their profile, and so on.
- // * Indirect actions by the candidate such as uploading a resume to a job
- // board that is collected by the agency through a feed, providing a resume to
- // a recruiter who then uploads it into the ATS, and so on.
- // * Updates made to the candidate's profile by the recruiter as a result of
- // interacting with the candidate (for example adding a skill or work
- // preference, and so on). Changes to [recruiting_notes][google.cloud.talent.v4beta1.Profile.recruiting_notes] are specifically
- // excluded from this action type.
- //
- // Note: [candidate_update_time][google.cloud.talent.v4beta1.Profile.candidate_update_time] must be greater than or equal to
- // [resume_update_time][google.cloud.talent.v4beta1.Profile.resume_update_time] or an error is thrown.
- google.protobuf.Timestamp candidate_update_time = 67;
-
- // The timestamp when the candidate's resume was added or updated on the
- // candidate's profile. Whether that resume was directly uploaded by a
- // candidate, pulled from a 3rd party job board feed, added by a recruiter,
- // and so on.
- //
- // If this field is updated, it's expected that [resume][google.cloud.talent.v4beta1.Profile.resume] is provided in
- // the create or update calls.
- google.protobuf.Timestamp resume_update_time = 68;
-
- // The resume representing this profile.
- Resume resume = 53;
-
- // The names of the candidate this profile references.
- //
- // Currently only one person name is supported.
- repeated PersonName person_names = 11;
-
- // The candidate's postal addresses. It's highly recommended to
- // input this information as accurately as possible to help improve search
- // quality. Here are some recommendations:
- //
- // * Provide [Address.usage][google.cloud.talent.v4beta1.Address.usage] if possible, especially if the address is
- // PERSONAL. During a search only personal addresses are considered. If there
- // is no such address, all addresses with unspecified usage are assumed to be
- // personal.
- // * Provide [Address.current][google.cloud.talent.v4beta1.Address.current] for the current address if possible. During
- // a search, only current addresses are considered. If there is no such
- // address, all addresses are assumed to be current.
- //
- // When displaying a candidate's addresses, it is sometimes desirable to limit
- // the number of addresses shown. In these cases we recommend that you display
- // the addresses in the following order of priority:
- // 1. [Address.usage][google.cloud.talent.v4beta1.Address.usage] is PERSONAL and [Address.current][google.cloud.talent.v4beta1.Address.current] is true.
- // 2. [Address.usage][google.cloud.talent.v4beta1.Address.usage] is PERSONAL and [Address.current][google.cloud.talent.v4beta1.Address.current] is false or not
- // set.
- // 3. [Address.usage][google.cloud.talent.v4beta1.Address.usage] is CONTACT_INFO_USAGE_UNSPECIFIED and
- // [Address.current][google.cloud.talent.v4beta1.Address.current] is true.
- // 4. [Address.usage][google.cloud.talent.v4beta1.Address.usage] is CONTACT_INFO_USAGE_UNSPECIFIED and
- // [Address.current][google.cloud.talent.v4beta1.Address.current] is false or not set.
- repeated Address addresses = 12;
-
- // The candidate's email addresses.
- repeated Email email_addresses = 13;
-
- // The candidate's phone number(s).
- repeated Phone phone_numbers = 14;
-
- // The candidate's personal URIs.
- repeated PersonalUri personal_uris = 15;
-
- // Available contact information besides [addresses][google.cloud.talent.v4beta1.Profile.addresses], [email_addresses][google.cloud.talent.v4beta1.Profile.email_addresses],
- // [phone_numbers][google.cloud.talent.v4beta1.Profile.phone_numbers] and [personal_uris][google.cloud.talent.v4beta1.Profile.personal_uris]. For example, Hang-out, Skype.
- repeated AdditionalContactInfo additional_contact_info = 16;
-
- // The employment history records of the candidate. It's highly recommended
- // to input this information as accurately as possible to help improve search
- // quality. Here are some recommendations:
- //
- // * Specify the start and end dates of the employment records.
- // * List different employment types separately, no matter how minor the
- // change is.
- // For example, only job title is changed from "software engineer" to "senior
- // software engineer".
- // * Provide [EmploymentRecord.is_current][google.cloud.talent.v4beta1.EmploymentRecord.is_current] for the current employment if
- // possible. If not, it's inferred from user inputs.
- //
- // The limitation for max number of employment records is 100.
- repeated EmploymentRecord employment_records = 17;
-
- // The education history record of the candidate. It's highly recommended to
- // input this information as accurately as possible to help improve search
- // quality. Here are some recommendations:
- //
- // * Specify the start and end dates of the education records.
- // * List each education type separately, no matter how minor the change is.
- // For example, the profile contains the education experience from the same
- // school but different degrees.
- // * Provide [EducationRecord.is_current][google.cloud.talent.v4beta1.EducationRecord.is_current] for the current education if
- // possible. If not, it's inferred from user inputs.
- //
- // The limitation for max number of education records is 100.
- repeated EducationRecord education_records = 18;
-
- // The skill set of the candidate. It's highly recommended to provide as
- // much information as possible to help improve the search quality.
- //
- // The limitation for max number of skills is 500.
- repeated Skill skills = 19;
-
- // The individual or collaborative activities which the candidate has
- // participated in, for example, open-source projects, class assignments that
- // aren't listed in [employment_records][google.cloud.talent.v4beta1.Profile.employment_records].
- //
- // The limitation for max number of activities is 50.
- repeated Activity activities = 20;
-
- // The publications published by the candidate.
- //
- // The limitation for max number of publications is 50.
- repeated Publication publications = 21;
-
- // The patents acquired by the candidate.
- repeated Patent patents = 22;
-
- // The certifications acquired by the candidate.
- repeated Certification certifications = 23;
-
- // Output only. The resource names of the candidate's applications.
- repeated string applications = 47 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. The resource names of the candidate's assignments.
- repeated string assignments = 48 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // A map of fields to hold both filterable and non-filterable custom profile
- // attributes that aren't covered by the provided structured fields. See
- // [CustomAttribute][google.cloud.talent.v4beta1.CustomAttribute] for more details.
- //
- // At most 100 filterable and at most 100 unfilterable keys are supported. If
- // limit is exceeded, an error is thrown. Custom attributes are `unfilterable`
- // by default. These are filterable when the `filterable` flag is set to
- // `true`.
- //
- // Numeric custom attributes: each key can only map to one numeric value,
- // otherwise an error is thrown. Client can also filter on numeric custom
- // attributes using '>', '<' or '=' operators.
- //
- // String custom attributes: each key can map up to 50 string values. For
- // filterable string value, each value has a byte size of no more than 256B.
- // For unfilterable string values, the maximum byte size of a single key is
- // 64B. An error is thrown for any request exceeding the limit.
- // The maximum total byte size is 10KB.
- map custom_attributes = 26;
-
- // Output only. Indicates if a summarized profile was created as part of the
- // profile creation API call. This flag does not indicate whether a profile is
- // searchable or not.
- bool processed = 27 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Keyword snippet shows how the search result is related to a
- // search query. This is only returned in [SearchProfilesResponse][google.cloud.talent.v4beta1.SearchProfilesResponse].
- string keyword_snippet = 28 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Candidate's availability signals.
- repeated AvailabilitySignal availability_signals = 70 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Derived locations of the profile, resolved from [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses].
- //
- // [derived_addresses][google.cloud.talent.v4beta1.Profile.derived_addresses] are exactly matched to [Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses] in the
- // same order.
- repeated Location derived_addresses = 64 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
-
-// Candidate availability signal.
-message AvailabilitySignal {
- // Type of signal.
- AvailabilitySignalType type = 1;
-
- // Timestamp of when the given availability activity last happened.
- google.protobuf.Timestamp last_update_time = 2;
-
- // Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
- // [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
- //
- // Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
- // in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
- // [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
- google.protobuf.BoolValue filter_satisfied = 3;
-}
-
-// Resource that represents a resume.
-message Resume {
- // The format of a structured resume.
- enum ResumeType {
- // Default value.
- RESUME_TYPE_UNSPECIFIED = 0;
-
- // The profile contents in HR-XML format.
- // See https://schemas.liquid-technologies.com/hr-xml/2007-04-15/ for more
- // information about Human Resources XML.
- HRXML = 1;
-
- // Resume type not specified.
- OTHER_RESUME_TYPE = 2;
- }
-
- // Users can create a profile with only this field field, if [resume_type][google.cloud.talent.v4beta1.Resume.resume_type]
- // is [HRXML][google.cloud.talent.v4beta1.Resume.ResumeType.HRXML]. For example, the API parses this field and
- // creates a profile
- // with all structured fields populated. [EmploymentRecord][google.cloud.talent.v4beta1.EmploymentRecord],
- // [EducationRecord][google.cloud.talent.v4beta1.EducationRecord], and so on. An error is thrown if this field cannot be
- // parsed.
- //
- // Note that the use of the functionality offered by this field to extract
- // data from resumes is an Alpha feature and as such is not covered by any
- // SLA.
- string structured_resume = 1;
-
- // The format of [structured_resume][google.cloud.talent.v4beta1.Resume.structured_resume].
- ResumeType resume_type = 2;
-}
-
-// Resource that represents the name of a person.
-message PersonName {
- // Resource that represents a person's structured name.
- message PersonStructuredName {
- // Given/first name.
- //
- // It's derived from [formatted_name][google.cloud.talent.v4beta1.PersonName.formatted_name] if not provided.
- //
- // Number of characters allowed is 100.
- string given_name = 1;
-
- // Preferred given/first name or nickname.
- //
- // Number of characters allowed is 100.
- string preferred_name = 6;
-
- // Middle initial.
- //
- // It's derived from [formatted_name][google.cloud.talent.v4beta1.PersonName.formatted_name] if not provided.
- //
- // Number of characters allowed is 20.
- string middle_initial = 2;
-
- // Family/last name.
- //
- // It's derived from [formatted_name][google.cloud.talent.v4beta1.PersonName.formatted_name] if not provided.
- //
- // Number of characters allowed is 100.
- string family_name = 3;
-
- // Suffixes.
- //
- // Number of characters allowed is 20.
- repeated string suffixes = 4;
-
- // Prefixes.
- //
- // Number of characters allowed is 20.
- repeated string prefixes = 5;
- }
-
- // The name of a person. It can be one of
- // [formatted_name][google.cloud.talent.v4beta1.PersonName.formatted_name] or
- // [structured_name][google.cloud.talent.v4beta1.PersonName.structured_name].
- oneof person_name {
- // A string represents a person's full name. For example, "Dr. John Smith".
- //
- // Number of characters allowed is 100.
- string formatted_name = 1;
-
- // A person's name in a structured way (last name, first name, suffix, and
- // so on.)
- PersonStructuredName structured_name = 2;
- }
-
- // Preferred name for the person. This field is ignored if [structured_name][google.cloud.talent.v4beta1.PersonName.structured_name]
- // is provided.
- //
- // Number of characters allowed is 100.
- string preferred_name = 3;
-}
-
-// Resource that represents a address.
-message Address {
- // The usage of the address. For example, SCHOOL, WORK, PERSONAL.
- ContactInfoUsage usage = 1;
-
- // The address of a person. It can be one of
- // [unstructured_address][google.cloud.talent.v4beta1.Address.unstructured_address] or
- // [structured_address][google.cloud.talent.v4beta1.Address.structured_address].
- oneof address {
- // Unstructured address.
- //
- // For example, "1600 Amphitheatre Pkwy, Mountain View, CA 94043",
- // "Sunnyvale, California".
- //
- // Number of characters allowed is 100.
- string unstructured_address = 2;
-
- // Structured address that contains street address, city, state, country,
- // and so on.
- google.type.PostalAddress structured_address = 3;
- }
-
- // Indicates if it's the person's current address.
- google.protobuf.BoolValue current = 4;
-}
-
-// Resource that represents a person's email address.
-message Email {
- // The usage of the email address. For example, SCHOOL, WORK, PERSONAL.
- ContactInfoUsage usage = 1;
-
- // Email address.
- //
- // Number of characters allowed is 4,000.
- string email_address = 2;
-}
-
-// Resource that represents a person's telephone number.
-message Phone {
- // Enum that represents the type of the telephone.
- enum PhoneType {
- // Default value.
- PHONE_TYPE_UNSPECIFIED = 0;
-
- // A landline.
- LANDLINE = 1;
-
- // A mobile.
- MOBILE = 2;
-
- // A fax.
- FAX = 3;
-
- // A pager.
- PAGER = 4;
-
- // A TTY (test telephone) or TDD (telecommunication device for the deaf).
- TTY_OR_TDD = 5;
-
- // A voicemail.
- VOICEMAIL = 6;
-
- // A virtual telephone number is a number that can be routed to another
- // number and managed by the user via Web, SMS, IVR, and so on. It is
- // associated with a particular person, and may be routed to either a MOBILE
- // or LANDLINE number. The [phone usage][google.cloud.talent.v4beta1.ContactInfoUsage] should
- // be set to PERSONAL for these phone types. Some more information can be
- // found here: https://en.wikipedia.org/wiki/Personal_Numbers
- VIRTUAL = 7;
-
- // Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
- VOIP = 8;
-
- // In some regions (e.g. the USA), it is impossible to distinguish between
- // fixed-line and mobile numbers by looking at the phone number itself.
- MOBILE_OR_LANDLINE = 9;
- }
-
- // The usage of the phone. For example, SCHOOL, WORK, PERSONAL.
- ContactInfoUsage usage = 1;
-
- // The phone type. For example, LANDLINE, MOBILE, FAX.
- PhoneType type = 2;
-
- // Phone number.
- //
- // Any phone formats are supported and only exact matches are performed on
- // searches. For example, if a phone number in profile is provided in the
- // format of "(xxx)xxx-xxxx", in profile searches the same phone format
- // has to be provided.
- //
- // Number of characters allowed is 20.
- string number = 3;
-
- // When this number is available. Any descriptive string is expected.
- //
- // Number of characters allowed is 100.
- string when_available = 4;
-}
-
-// Resource that represents a valid URI for a personal use.
-message PersonalUri {
- // The personal URI.
- //
- // Number of characters allowed is 4,000.
- string uri = 1;
-}
-
-// Resource that represents contact information other than phone, email,
-// URI and addresses.
-message AdditionalContactInfo {
- // The usage of this contact method. For example, SCHOOL, WORK, PERSONAL.
- ContactInfoUsage usage = 1;
-
- // The name of the contact method.
- //
- // For example, "hangout", "skype".
- //
- // Number of characters allowed is 100.
- string name = 2;
-
- // The contact id.
- //
- // Number of characters allowed is 100.
- string contact_id = 3;
-}
-
-// Resource that represents an employment record of a candidate.
-message EmploymentRecord {
- // Start date of the employment.
- google.type.Date start_date = 1;
-
- // End date of the employment.
- google.type.Date end_date = 2;
-
- // The name of the employer company/organization.
- //
- // For example, "Google", "Alphabet", and so on.
- //
- // Number of characters allowed is 250.
- string employer_name = 3;
-
- // The division name of the employment.
- //
- // For example, division, department, client, and so on.
- //
- // Number of characters allowed is 100.
- string division_name = 4;
-
- // The physical address of the employer.
- Address address = 5;
-
- // The job title of the employment.
- //
- // For example, "Software Engineer", "Data Scientist", and so on.
- //
- // Number of characters allowed is 250.
- string job_title = 6;
-
- // The description of job content.
- //
- // Number of characters allowed is 100,000.
- string job_description = 7;
-
- // If the jobs is a supervisor position.
- google.protobuf.BoolValue is_supervisor = 8;
-
- // If this employment is self-employed.
- google.protobuf.BoolValue is_self_employed = 9;
-
- // If this employment is current.
- google.protobuf.BoolValue is_current = 10;
-
- // Output only. The job title snippet shows how the [job_title][google.cloud.talent.v4beta1.EmploymentRecord.job_title] is related
- // to a search query. It's empty if the [job_title][google.cloud.talent.v4beta1.EmploymentRecord.job_title] isn't related to the
- // search query.
- string job_title_snippet = 11 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. The job description snippet shows how the [job_description][google.cloud.talent.v4beta1.EmploymentRecord.job_description]
- // is related to a search query. It's empty if the [job_description][google.cloud.talent.v4beta1.EmploymentRecord.job_description] isn't
- // related to the search query.
- string job_description_snippet = 12 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. The employer name snippet shows how the [employer_name][google.cloud.talent.v4beta1.EmploymentRecord.employer_name] is
- // related to a search query. It's empty if the [employer_name][google.cloud.talent.v4beta1.EmploymentRecord.employer_name] isn't
- // related to the search query.
- string employer_name_snippet = 13 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
-
-// Resource that represents an education record of a candidate.
-message EducationRecord {
- // The start date of the education.
- google.type.Date start_date = 1;
-
- // The end date of the education.
- google.type.Date end_date = 2;
-
- // The expected graduation date if currently pursuing a degree.
- google.type.Date expected_graduation_date = 3;
-
- // The name of the school or institution.
- //
- // For example, "Stanford University", "UC Berkeley", and so on.
- //
- // Number of characters allowed is 250.
- string school_name = 4;
-
- // The physical address of the education institution.
- Address address = 5;
-
- // The degree information. It can be one of
- // [degree_description][google.cloud.talent.v4beta1.EducationRecord.degree_description] or
- // [structured_degree][google.cloud.talent.v4beta1.EducationRecord.structured_degree].
- oneof degree {
- // The full description of the degree.
- //
- // For example, "Master of Science in Computer Science", "B.S in Math".
- //
- // Number of characters allowed is 100.
- string degree_description = 6;
-
- // The structured notation of the degree.
- Degree structured_degree = 7;
- }
-
- // The description of the education.
- //
- // Number of characters allowed is 100,000.
- string description = 8;
-
- // If this education is current.
- google.protobuf.BoolValue is_current = 9;
-
- // Output only. The school name snippet shows how the [school_name][google.cloud.talent.v4beta1.EducationRecord.school_name] is related to a
- // search query in search result. It's empty if the [school_name][google.cloud.talent.v4beta1.EducationRecord.school_name] isn't
- // related to the search query.
- string school_name_snippet = 10 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. The job description snippet shows how the [Degree][google.cloud.talent.v4beta1.Degree] is related to a search
- // query in search result. It's empty if the [Degree][google.cloud.talent.v4beta1.Degree] isn't related to the
- // search query.
- string degree_snippet = 11 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
-
-// Resource that represents a degree pursuing or acquired by a candidate.
-message Degree {
- // ISCED degree type.
- DegreeType degree_type = 1;
-
- // Full Degree name.
- //
- // For example, "B.S.", "Master of Arts", and so on.
- //
- // Number of characters allowed is 100.
- string degree_name = 2;
-
- // Fields of study for the degree.
- //
- // For example, "Computer science", "engineering".
- //
- // Number of characters allowed is 100.
- repeated string fields_of_study = 3;
-}
-
-// Resource that represents an individual or collaborative activity participated
-// in by a candidate, for example, an open-source project, a class assignment,
-// and so on.
-message Activity {
- // Activity display name.
- //
- // Number of characters allowed is 100.
- string display_name = 1;
-
- // Activity description.
- //
- // Number of characters allowed is 100,000.
- string description = 2;
-
- // Activity URI.
- //
- // Number of characters allowed is 4,000.
- string uri = 3;
-
- // The first creation date of the activity.
- google.type.Date create_date = 4;
-
- // The last update date of the activity.
- google.type.Date update_date = 5;
-
- // A list of team members involved in this activity.
- //
- // Number of characters allowed is 100.
- //
- // The limitation for max number of team members is 50.
- repeated string team_members = 6;
-
- // A list of skills used in this activity.
- //
- // The limitation for max number of skills used is 50.
- repeated Skill skills_used = 7;
-
- // Output only. Activity name snippet shows how the [display_name][google.cloud.talent.v4beta1.Activity.display_name] is related to a search
- // query. It's empty if the [display_name][google.cloud.talent.v4beta1.Activity.display_name] isn't related to the search
- // query.
- string activity_name_snippet = 8 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Activity description snippet shows how the
- // [description][google.cloud.talent.v4beta1.Activity.description] is related to a search query. It's empty if the
- // [description][google.cloud.talent.v4beta1.Activity.description] isn't related to the search query.
- string activity_description_snippet = 9 [(google.api.field_behavior) = OUTPUT_ONLY];
-
- // Output only. Skill used snippet shows how the corresponding
- // [skills_used][google.cloud.talent.v4beta1.Activity.skills_used] are related to a search query. It's empty if the
- // corresponding [skills_used][google.cloud.talent.v4beta1.Activity.skills_used] are not related to the search query.
- repeated string skills_used_snippet = 10 [(google.api.field_behavior) = OUTPUT_ONLY];
-}
-
-// Resource that represents a publication resource of a candidate.
-message Publication {
- // A list of author names.
- //
- // Number of characters allowed is 100.
- repeated string authors = 1;
-
- // The title of the publication.
- //
- // Number of characters allowed is 100.
- string title = 2;
-
- // The description of the publication.
- //
- // Number of characters allowed is 100,000.
- string description = 3;
-
- // The journal name of the publication.
- //
- // Number of characters allowed is 100.
- string journal = 4;
-
- // Volume number.
- //
- // Number of characters allowed is 100.
- string volume = 5;
-
- // The publisher of the journal.
- //
- // Number of characters allowed is 100.
- string publisher = 6;
-
- // The publication date.
- google.type.Date publication_date = 7;
-
- // The publication type.
- //
- // Number of characters allowed is 100.
- string publication_type = 8;
-
- // ISBN number.
- //
- // Number of characters allowed is 100.
- string isbn = 9;
-}
-
-// Resource that represents the patent acquired by a candidate.
-message Patent {
- // Name of the patent.
- //
- // Number of characters allowed is 100.
- string display_name = 1;
-
- // A list of inventors' names.
- //
- // Number of characters allowed for each is 100.
- repeated string inventors = 2;
-
- // The status of the patent.
- //
- // Number of characters allowed is 100.
- string patent_status = 3;
-
- // The date the last time the status of the patent was checked.
- google.type.Date patent_status_date = 4;
-
- // The date that the patent was filed.
- google.type.Date patent_filing_date = 5;
-
- // The name of the patent office.
- //
- // Number of characters allowed is 100.
- string patent_office = 6;
-
- // The number of the patent.
- //
- // Number of characters allowed is 100.
- string patent_number = 7;
-
- // The description of the patent.
- //
- // Number of characters allowed is 100,000.
- string patent_description = 8;
-
- // The skills used in this patent.
- repeated Skill skills_used = 9;
-}
diff --git a/google/cloud/talent_v4beta1/proto/profile_service.proto b/google/cloud/talent_v4beta1/proto/profile_service.proto
deleted file mode 100644
index 4a153fd2..00000000
--- a/google/cloud/talent_v4beta1/proto/profile_service.proto
+++ /dev/null
@@ -1,467 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/cloud/talent/v4beta1/filters.proto";
-import "google/cloud/talent/v4beta1/histogram.proto";
-import "google/cloud/talent/v4beta1/profile.proto";
-import "google/longrunning/operations.proto";
-import "google/protobuf/any.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-import "google/rpc/status.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "ProfileServiceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A service that handles profile management, including profile CRUD,
-// enumeration and search.
-service ProfileService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Lists profiles by filter. The order is unspecified.
- rpc ListProfiles(ListProfilesRequest) returns (ListProfilesResponse) {
- option (google.api.http) = {
- get: "/v4beta1/{parent=projects/*/tenants/*}/profiles"
- };
- option (google.api.method_signature) = "parent";
- }
-
- // Creates and returns a new profile.
- rpc CreateProfile(CreateProfileRequest) returns (Profile) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}/profiles"
- body: "*"
- };
- option (google.api.method_signature) = "parent,profile";
- }
-
- // Gets the specified profile.
- rpc GetProfile(GetProfileRequest) returns (Profile) {
- option (google.api.http) = {
- get: "/v4beta1/{name=projects/*/tenants/*/profiles/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates the specified profile and returns the updated result.
- rpc UpdateProfile(UpdateProfileRequest) returns (Profile) {
- option (google.api.http) = {
- patch: "/v4beta1/{profile.name=projects/*/tenants/*/profiles/*}"
- body: "*"
- };
- option (google.api.method_signature) = "profile";
- }
-
- // Deletes the specified profile.
- // Prerequisite: The profile has no associated applications or assignments
- // associated.
- rpc DeleteProfile(DeleteProfileRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4beta1/{name=projects/*/tenants/*/profiles/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Searches for profiles within a tenant.
- //
- // For example, search by raw queries "software engineer in Mountain View" or
- // search by structured filters (location filter, education filter, etc.).
- //
- // See [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest] for more information.
- rpc SearchProfiles(SearchProfilesRequest) returns (SearchProfilesResponse) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*/tenants/*}:search"
- body: "*"
- };
- }
-}
-
-// List profiles request.
-message ListProfilesRequest {
- // Required. The resource name of the tenant under which the profile is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- child_type: "jobs.googleapis.com/Profile"
- }
- ];
-
- // The filter string specifies the profiles to be enumerated.
- //
- // Supported operator: =, AND
- //
- // The field(s) eligible for filtering are:
- //
- // * `externalId`
- // * `groupId`
- //
- // externalId and groupId cannot be specified at the same time. If both
- // externalId and groupId are provided, the API will return a bad request
- // error.
- //
- // Sample Query:
- //
- // * externalId = "externalId-1"
- // * groupId = "groupId-1"
- string filter = 5;
-
- // The token that specifies the current offset (that is, starting result).
- //
- // Please set the value to [ListProfilesResponse.next_page_token][google.cloud.talent.v4beta1.ListProfilesResponse.next_page_token] to
- // continue the list.
- string page_token = 2;
-
- // The maximum number of profiles to be returned, at most 100.
- //
- // Default is 100 unless a positive number smaller than 100 is specified.
- int32 page_size = 3;
-
- // A field mask to specify the profile fields to be listed in response.
- // All fields are listed if it is unset.
- //
- // Valid values are:
- //
- // * name
- google.protobuf.FieldMask read_mask = 4;
-}
-
-// The List profiles response object.
-message ListProfilesResponse {
- // Profiles for the specific tenant.
- repeated Profile profiles = 1;
-
- // A token to retrieve the next page of results. This is empty if there are no
- // more results.
- string next_page_token = 2;
-}
-
-// Create profile request.
-message CreateProfileRequest {
- // Required. The name of the tenant this profile belongs to.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-
- // Required. The profile to be created.
- Profile profile = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Get profile request.
-message GetProfileRequest {
- // Required. Resource name of the profile to get.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}". For
- // example, "projects/foo/tenants/bar/profiles/baz".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Profile"
- }
- ];
-}
-
-// Update profile request
-message UpdateProfileRequest {
- // Required. Profile to be updated.
- Profile profile = 1 [(google.api.field_behavior) = REQUIRED];
-
- // A field mask to specify the profile fields to update.
- //
- // A full update is performed if it is unset.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Delete profile request.
-message DeleteProfileRequest {
- // Required. Resource name of the profile to be deleted.
- //
- // The format is
- // "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}". For
- // example, "projects/foo/tenants/bar/profiles/baz".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Profile"
- }
- ];
-}
-
-// The request body of the `SearchProfiles` call.
-message SearchProfilesRequest {
- // Required. The resource name of the tenant to search within.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}". For example,
- // "projects/foo/tenants/bar".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-
- // Required. The meta information collected about the profile search user. This is used
- // to improve the search quality of the service. These values are provided by
- // users, and must be precise and consistent.
- RequestMetadata request_metadata = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Search query to execute. See [ProfileQuery][google.cloud.talent.v4beta1.ProfileQuery] for more details.
- ProfileQuery profile_query = 3;
-
- // A limit on the number of profiles returned in the search results.
- // A value above the default value 10 can increase search response time.
- //
- // The maximum value allowed is 100. Otherwise an error is thrown.
- int32 page_size = 4;
-
- // The pageToken, similar to offset enables users of the API to paginate
- // through the search results. To retrieve the first page of results, set the
- // pageToken to empty. The search response includes a
- // [nextPageToken][google.cloud.talent.v4beta1.SearchProfilesResponse.next_page_token] field that can be
- // used to populate the pageToken field for the next page of results. Using
- // pageToken instead of offset increases the performance of the API,
- // especially compared to larger offset values.
- string page_token = 5;
-
- // An integer that specifies the current offset (that is, starting result) in
- // search results. This field is only considered if [page_token][google.cloud.talent.v4beta1.SearchProfilesRequest.page_token] is unset.
- //
- // The maximum allowed value is 5000. Otherwise an error is thrown.
- //
- // For example, 0 means to search from the first profile, and 10 means to
- // search from the 11th profile. This can be used for pagination, for example
- // pageSize = 10 and offset = 10 means to search from the second page.
- int32 offset = 6;
-
- // This flag controls the spell-check feature. If `false`, the
- // service attempts to correct a misspelled query.
- //
- // For example, "enginee" is corrected to "engineer".
- bool disable_spell_check = 7;
-
- // The criteria that determines how search results are sorted.
- // Defaults is "relevance desc" if no value is specified.
- //
- // Supported options are:
- //
- // * "relevance desc": By descending relevance, as determined by the API
- // algorithms.
- // * "update_date desc": Sort by [Profile.update_time][google.cloud.talent.v4beta1.Profile.update_time] in descending order
- // (recently updated profiles first).
- // * "create_date desc": Sort by [Profile.create_time][google.cloud.talent.v4beta1.Profile.create_time] in descending order
- // (recently created profiles first).
- // * "first_name": Sort by [PersonName.PersonStructuredName.given_name][google.cloud.talent.v4beta1.PersonName.PersonStructuredName.given_name] in
- // ascending order.
- // * "first_name desc": Sort by [PersonName.PersonStructuredName.given_name][google.cloud.talent.v4beta1.PersonName.PersonStructuredName.given_name]
- // in descending order.
- // * "last_name": Sort by [PersonName.PersonStructuredName.family_name][google.cloud.talent.v4beta1.PersonName.PersonStructuredName.family_name] in
- // ascending order.
- // * "last_name desc": Sort by [PersonName.PersonStructuredName.family_name][google.cloud.talent.v4beta1.PersonName.PersonStructuredName.family_name]
- // in ascending order.
- string order_by = 8;
-
- // When sort by field is based on alphabetical order, sort values case
- // sensitively (based on ASCII) when the value is set to true. Default value
- // is case in-sensitive sort (false).
- bool case_sensitive_sort = 9;
-
- // A list of expressions specifies histogram requests against matching
- // profiles for [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest].
- //
- // The expression syntax looks like a function definition with parameters.
- //
- // Function syntax: function_name(histogram_facet[, list of buckets])
- //
- // Data types:
- //
- // * Histogram facet: facet names with format [a-zA-Z][a-zA-Z0-9_]+.
- // * String: string like "any string with backslash escape for quote(\")."
- // * Number: whole number and floating point number like 10, -1 and -0.01.
- // * List: list of elements with comma(,) separator surrounded by square
- // brackets. For example, [1, 2, 3] and ["one", "two", "three"].
- //
- // Built-in constants:
- //
- // * MIN (minimum number similar to java Double.MIN_VALUE)
- // * MAX (maximum number similar to java Double.MAX_VALUE)
- //
- // Built-in functions:
- //
- // * bucket(start, end[, label])
- // Bucket build-in function creates a bucket with range of [start, end). Note
- // that the end is exclusive.
- // For example, bucket(1, MAX, "positive number") or bucket(1, 10).
- //
- // Histogram Facets:
- //
- // * admin1: Admin1 is a global placeholder for referring to state, province,
- // or the particular term a country uses to define the geographic structure
- // below the country level. Examples include states codes such as "CA", "IL",
- // "NY", and provinces, such as "BC".
- // * locality: Locality is a global placeholder for referring to city, town,
- // or the particular term a country uses to define the geographic structure
- // below the admin1 level. Examples include city names such as
- // "Mountain View" and "New York".
- // * extended_locality: Extended locality is concatenated version of admin1
- // and locality with comma separator. For example, "Mountain View, CA" and
- // "New York, NY".
- // * postal_code: Postal code of profile which follows locale code.
- // * country: Country code (ISO-3166-1 alpha-2 code) of profile, such as US,
- // JP, GB.
- // * job_title: Normalized job titles specified in EmploymentHistory.
- // * company_name: Normalized company name of profiles to match on.
- // * institution: The school name. For example, "MIT",
- // "University of California, Berkeley"
- // * degree: Highest education degree in ISCED code. Each value in degree
- // covers a specific level of education, without any expansion to upper nor
- // lower levels of education degree.
- // * experience_in_months: experience in months. 0 means 0 month to 1 month
- // (exclusive).
- // * application_date: The application date specifies application start dates.
- // See [ApplicationDateFilter][google.cloud.talent.v4beta1.ApplicationDateFilter] for more details.
- // * application_outcome_notes: The application outcome reason specifies the
- // reasons behind the outcome of the job application.
- // See [ApplicationOutcomeNotesFilter][google.cloud.talent.v4beta1.ApplicationOutcomeNotesFilter] for more details.
- // * application_job_title: The application job title specifies the job
- // applied for in the application.
- // See [ApplicationJobFilter][google.cloud.talent.v4beta1.ApplicationJobFilter] for more details.
- // * hirable_status: Hirable status specifies the profile's hirable status.
- // * string_custom_attribute: String custom attributes. Values can be accessed
- // via square bracket notation like string_custom_attribute["key1"].
- // * numeric_custom_attribute: Numeric custom attributes. Values can be
- // accessed via square bracket notation like numeric_custom_attribute["key1"].
- //
- // Example expressions:
- //
- // * count(admin1)
- // * count(experience_in_months, [bucket(0, 12, "1 year"),
- // bucket(12, 36, "1-3 years"), bucket(36, MAX, "3+ years")])
- // * count(string_custom_attribute["assigned_recruiter"])
- // * count(numeric_custom_attribute["favorite_number"],
- // [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative")])
- repeated HistogramQuery histogram_queries = 10;
-
- // An id that uniquely identifies the result set of a
- // [SearchProfiles][google.cloud.talent.v4beta1.ProfileService.SearchProfiles] call. The id should be
- // retrieved from the
- // [SearchProfilesResponse][google.cloud.talent.v4beta1.SearchProfilesResponse] message returned from a previous
- // invocation of [SearchProfiles][google.cloud.talent.v4beta1.ProfileService.SearchProfiles].
- //
- // A result set is an ordered list of search results.
- //
- // If this field is not set, a new result set is computed based on the
- // [profile_query][google.cloud.talent.v4beta1.SearchProfilesRequest.profile_query]. A new [result_set_id][google.cloud.talent.v4beta1.SearchProfilesRequest.result_set_id] is returned as a handle to
- // access this result set.
- //
- // If this field is set, the service will ignore the resource and
- // [profile_query][google.cloud.talent.v4beta1.SearchProfilesRequest.profile_query] values, and simply retrieve a page of results from the
- // corresponding result set. In this case, one and only one of [page_token][google.cloud.talent.v4beta1.SearchProfilesRequest.page_token]
- // or [offset][google.cloud.talent.v4beta1.SearchProfilesRequest.offset] must be set.
- //
- // A typical use case is to invoke [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest] without this
- // field, then use the resulting [result_set_id][google.cloud.talent.v4beta1.SearchProfilesRequest.result_set_id] in
- // [SearchProfilesResponse][google.cloud.talent.v4beta1.SearchProfilesResponse] to page through the results.
- string result_set_id = 12;
-
- // This flag is used to indicate whether the service will attempt to
- // understand synonyms and terms related to the search query or treat the
- // query "as is" when it generates a set of results. By default this flag is
- // set to false, thus allowing expanded results to also be returned. For
- // example a search for "software engineer" might also return candidates who
- // have experience in jobs similar to software engineer positions. By setting
- // this flag to true, the service will only attempt to deliver candidates has
- // software engineer in his/her global fields by treating "software engineer"
- // as a keyword.
- //
- // It is recommended to provide a feature in the UI (such as a checkbox) to
- // allow recruiters to set this flag to true if they intend to search for
- // longer boolean strings.
- bool strict_keywords_search = 13;
-}
-
-// Response of SearchProfiles method.
-message SearchProfilesResponse {
- // An estimation of the number of profiles that match the specified query.
- //
- // This number isn't guaranteed to be accurate.
- int64 estimated_total_size = 1;
-
- // The spell checking result, and correction.
- SpellingCorrection spell_correction = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-
- // A token to retrieve the next page of results. This is empty if there are no
- // more results.
- string next_page_token = 4;
-
- // The histogram results that match with specified
- // [SearchProfilesRequest.histogram_queries][google.cloud.talent.v4beta1.SearchProfilesRequest.histogram_queries].
- repeated HistogramQueryResult histogram_query_results = 5;
-
- // The profile entities that match the specified [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest].
- repeated SummarizedProfile summarized_profiles = 6;
-
- // An id that uniquely identifies the result set of a
- // [SearchProfiles][google.cloud.talent.v4beta1.ProfileService.SearchProfiles] call for consistent
- // results.
- string result_set_id = 7;
-}
-
-// Profile entry with metadata inside [SearchProfilesResponse][google.cloud.talent.v4beta1.SearchProfilesResponse].
-message SummarizedProfile {
- // A list of profiles that are linked by [Profile.group_id][google.cloud.talent.v4beta1.Profile.group_id].
- repeated Profile profiles = 1;
-
- // A profile summary shows the profile summary and how the profile matches the
- // search query.
- //
- // In profile summary, the profiles with the same [Profile.group_id][google.cloud.talent.v4beta1.Profile.group_id] are
- // merged together. Among profiles, same education/employment records may be
- // slightly different but they are merged into one with best efforts.
- //
- // For example, in one profile the school name is "UC Berkeley" and the field
- // study is "Computer Science" and in another one the school name is
- // "University of California at Berkeley" and the field study is "CS". The API
- // merges these two inputs into one and selects one value for each field. For
- // example, the school name in summary is set to "University of California at
- // Berkeley" and the field of study is set to "Computer Science".
- Profile summary = 2;
-}
diff --git a/google/cloud/talent_v4beta1/proto/tenant.proto b/google/cloud/talent_v4beta1/proto/tenant.proto
deleted file mode 100644
index 0328c143..00000000
--- a/google/cloud/talent_v4beta1/proto/tenant.proto
+++ /dev/null
@@ -1,81 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/protobuf/timestamp.proto";
-import "google/api/annotations.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "TenantResourceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A Tenant resource represents a tenant in the service. A tenant is a group or
-// entity that shares common access with specific privileges for resources like
-// profiles. Customer may create multiple tenants to provide data isolation for
-// different groups.
-message Tenant {
- option (google.api.resource) = {
- type: "jobs.googleapis.com/Tenant"
- pattern: "projects/{project}/tenants/{tenant}"
- };
-
- // Enum that represents how user data owned by the tenant is used.
- enum DataUsageType {
- // Default value.
- DATA_USAGE_TYPE_UNSPECIFIED = 0;
-
- // Data owned by this tenant is used to improve search/recommendation
- // quality across tenants.
- AGGREGATED = 1;
-
- // Data owned by this tenant is used to improve search/recommendation
- // quality for this tenant only.
- ISOLATED = 2;
- }
-
- // Required during tenant update.
- //
- // The resource name for a tenant. This is generated by the service when a
- // tenant is created.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string name = 1;
-
- // Required. Client side tenant identifier, used to uniquely identify the tenant.
- //
- // The maximum number of allowed characters is 255.
- string external_id = 2 [(google.api.field_behavior) = REQUIRED];
-
- // Indicates whether data owned by this tenant may be used to provide product
- // improvements across other tenants.
- //
- // Defaults behavior is [DataUsageType.ISOLATED][google.cloud.talent.v4beta1.Tenant.DataUsageType.ISOLATED] if it's unset.
- DataUsageType usage_type = 3;
-
- // A list of keys of filterable [Profile.custom_attributes][google.cloud.talent.v4beta1.Profile.custom_attributes], whose
- // corresponding `string_values` are used in keyword searches. Profiles with
- // `string_values` under these specified field keys are returned if any
- // of the values match the search keyword. Custom field values with
- // parenthesis, brackets and special symbols are not searchable as-is,
- // and must be surrounded by quotes.
- repeated string keyword_searchable_profile_custom_attributes = 4;
-}
diff --git a/google/cloud/talent_v4beta1/proto/tenant_service.proto b/google/cloud/talent_v4beta1/proto/tenant_service.proto
deleted file mode 100644
index 3eb260d8..00000000
--- a/google/cloud/talent_v4beta1/proto/tenant_service.proto
+++ /dev/null
@@ -1,176 +0,0 @@
-// 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.
-
-syntax = "proto3";
-
-package google.cloud.talent.v4beta1;
-
-import "google/api/annotations.proto";
-import "google/api/client.proto";
-import "google/api/field_behavior.proto";
-import "google/api/resource.proto";
-import "google/cloud/talent/v4beta1/common.proto";
-import "google/cloud/talent/v4beta1/tenant.proto";
-import "google/protobuf/empty.proto";
-import "google/protobuf/field_mask.proto";
-
-option go_package = "google.golang.org/genproto/googleapis/cloud/talent/v4beta1;talent";
-option java_multiple_files = true;
-option java_outer_classname = "TenantServiceProto";
-option java_package = "com.google.cloud.talent.v4beta1";
-option objc_class_prefix = "CTS";
-
-// A service that handles tenant management, including CRUD and enumeration.
-service TenantService {
- option (google.api.default_host) = "jobs.googleapis.com";
- option (google.api.oauth_scopes) =
- "https://www.googleapis.com/auth/cloud-platform,"
- "https://www.googleapis.com/auth/jobs";
-
- // Creates a new tenant entity.
- rpc CreateTenant(CreateTenantRequest) returns (Tenant) {
- option (google.api.http) = {
- post: "/v4beta1/{parent=projects/*}/tenants"
- body: "*"
- };
- option (google.api.method_signature) = "parent,tenant";
- }
-
- // Retrieves specified tenant.
- rpc GetTenant(GetTenantRequest) returns (Tenant) {
- option (google.api.http) = {
- get: "/v4beta1/{name=projects/*/tenants/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Updates specified tenant.
- rpc UpdateTenant(UpdateTenantRequest) returns (Tenant) {
- option (google.api.http) = {
- patch: "/v4beta1/{tenant.name=projects/*/tenants/*}"
- body: "*"
- };
- option (google.api.method_signature) = "tenant";
- }
-
- // Deletes specified tenant.
- rpc DeleteTenant(DeleteTenantRequest) returns (google.protobuf.Empty) {
- option (google.api.http) = {
- delete: "/v4beta1/{name=projects/*/tenants/*}"
- };
- option (google.api.method_signature) = "name";
- }
-
- // Lists all tenants associated with the project.
- rpc ListTenants(ListTenantsRequest) returns (ListTenantsResponse) {
- option (google.api.http) = {
- get: "/v4beta1/{parent=projects/*}/tenants"
- };
- option (google.api.method_signature) = "parent";
- }
-}
-
-// The Request of the CreateTenant method.
-message CreateTenantRequest {
- // Required. Resource name of the project under which the tenant is created.
- //
- // The format is "projects/{project_id}", for example,
- // "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "cloudresourcemanager.googleapis.com/Project"
- }
- ];
-
- // Required. The tenant to be created.
- Tenant tenant = 2 [(google.api.field_behavior) = REQUIRED];
-}
-
-// Request for getting a tenant by name.
-message GetTenantRequest {
- // Required. The resource name of the tenant to be retrieved.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-}
-
-// Request for updating a specified tenant.
-message UpdateTenantRequest {
- // Required. The tenant resource to replace the current resource in the system.
- Tenant tenant = 1 [(google.api.field_behavior) = REQUIRED];
-
- // Strongly recommended for the best service experience.
- //
- // If [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] is provided, only the specified fields in
- // [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are updated. Otherwise all the fields are updated.
- //
- // A field mask to specify the tenant fields to be updated. Only
- // top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are supported.
- google.protobuf.FieldMask update_mask = 2;
-}
-
-// Request to delete a tenant.
-message DeleteTenantRequest {
- // Required. The resource name of the tenant to be deleted.
- //
- // The format is "projects/{project_id}/tenants/{tenant_id}", for example,
- // "projects/foo/tenants/bar".
- string name = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "jobs.googleapis.com/Tenant"
- }
- ];
-}
-
-// List tenants for which the client has ACL visibility.
-message ListTenantsRequest {
- // Required. Resource name of the project under which the tenant is created.
- //
- // The format is "projects/{project_id}", for example,
- // "projects/foo".
- string parent = 1 [
- (google.api.field_behavior) = REQUIRED,
- (google.api.resource_reference) = {
- type: "cloudresourcemanager.googleapis.com/Project"
- }
- ];
-
- // The starting indicator from which to return results.
- string page_token = 2;
-
- // The maximum number of tenants to be returned, at most 100.
- // Default is 100 if a non-positive number is provided.
- int32 page_size = 3;
-}
-
-// The List tenants response object.
-message ListTenantsResponse {
- // Tenants for the current client.
- repeated Tenant tenants = 1;
-
- // A token to retrieve the next page of results.
- string next_page_token = 2;
-
- // Additional information for the API invocation, such as the request
- // tracking id.
- ResponseMetadata metadata = 3;
-}
diff --git a/google/cloud/talent_v4beta1/services/__init__.py b/google/cloud/talent_v4beta1/services/__init__.py
index 42ffdf2b..4de65971 100644
--- a/google/cloud/talent_v4beta1/services/__init__.py
+++ b/google/cloud/talent_v4beta1/services/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/google/cloud/talent_v4beta1/services/application_service/__init__.py b/google/cloud/talent_v4beta1/services/application_service/__init__.py
index 66c21a02..50257a2a 100644
--- a/google/cloud/talent_v4beta1/services/application_service/__init__.py
+++ b/google/cloud/talent_v4beta1/services/application_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import ApplicationServiceClient
from .async_client import ApplicationServiceAsyncClient
diff --git a/google/cloud/talent_v4beta1/services/application_service/async_client.py b/google/cloud/talent_v4beta1/services/application_service/async_client.py
index 8236846b..cb16cd6d 100644
--- a/google/cloud/talent_v4beta1/services/application_service/async_client.py
+++ b/google/cloud/talent_v4beta1/services/application_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,10 +20,10 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.services.application_service import pagers
@@ -33,10 +31,9 @@
from google.cloud.talent_v4beta1.types import application as gct_application
from google.cloud.talent_v4beta1.types import application_service
from google.cloud.talent_v4beta1.types import common
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
from .transports.base import ApplicationServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import ApplicationServiceGrpcAsyncIOTransport
from .client import ApplicationServiceClient
@@ -62,42 +59,67 @@ class ApplicationServiceAsyncClient:
parse_job_path = staticmethod(ApplicationServiceClient.parse_job_path)
profile_path = staticmethod(ApplicationServiceClient.profile_path)
parse_profile_path = staticmethod(ApplicationServiceClient.parse_profile_path)
-
common_billing_account_path = staticmethod(
ApplicationServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
ApplicationServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(ApplicationServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(
ApplicationServiceClient.parse_common_folder_path
)
-
common_organization_path = staticmethod(
ApplicationServiceClient.common_organization_path
)
parse_common_organization_path = staticmethod(
ApplicationServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(ApplicationServiceClient.common_project_path)
parse_common_project_path = staticmethod(
ApplicationServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(ApplicationServiceClient.common_location_path)
parse_common_location_path = staticmethod(
ApplicationServiceClient.parse_common_location_path
)
- from_service_account_file = ApplicationServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ ApplicationServiceAsyncClient: The constructed client.
+ """
+ return ApplicationServiceClient.from_service_account_info.__func__(ApplicationServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ ApplicationServiceAsyncClient: The constructed client.
+ """
+ return ApplicationServiceClient.from_service_account_file.__func__(ApplicationServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> ApplicationServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
ApplicationServiceTransport: The transport used by the client instance.
@@ -112,12 +134,12 @@ def transport(self) -> ApplicationServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, ApplicationServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the application service client.
+ """Instantiates the application service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -149,7 +171,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = ApplicationServiceClient(
credentials=credentials,
transport=transport,
@@ -170,7 +191,7 @@ async def create_application(
r"""Creates a new application entity.
Args:
- request (:class:`~.application_service.CreateApplicationRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.CreateApplicationRequest`):
The request object. The Request of the CreateApplication
method.
parent (:class:`str`):
@@ -180,16 +201,17 @@ async def create_application(
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
For example, "projects/foo/tenants/bar/profiles/baz".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- application (:class:`~.gct_application.Application`):
+ application (:class:`google.cloud.talent_v4beta1.types.Application`):
Required. The application to be
created.
+
This corresponds to the ``application`` 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.
@@ -197,7 +219,7 @@ async def create_application(
sent along with the request as metadata.
Returns:
- ~.gct_application.Application:
+ google.cloud.talent_v4beta1.types.Application:
Resource that represents a job
application record of a candidate.
@@ -216,7 +238,6 @@ async def create_application(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if application is not None:
@@ -254,7 +275,7 @@ async def get_application(
r"""Retrieves specified application.
Args:
- request (:class:`~.application_service.GetApplicationRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.GetApplicationRequest`):
The request object. Request for getting a application by
name.
name (:class:`str`):
@@ -265,10 +286,10 @@ async def get_application(
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}/applications/{application_id}".
For example,
"projects/foo/tenants/bar/profiles/baz/applications/qux".
+
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.
@@ -276,7 +297,7 @@ async def get_application(
sent along with the request as metadata.
Returns:
- ~.application.Application:
+ google.cloud.talent_v4beta1.types.Application:
Resource that represents a job
application record of a candidate.
@@ -295,7 +316,6 @@ async def get_application(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -308,8 +328,10 @@ async def get_application(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -339,17 +361,17 @@ async def update_application(
r"""Updates specified application.
Args:
- request (:class:`~.application_service.UpdateApplicationRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.UpdateApplicationRequest`):
The request object. Request for updating a specified
application.
- application (:class:`~.gct_application.Application`):
+ application (:class:`google.cloud.talent_v4beta1.types.Application`):
Required. The application resource to
replace the current resource in the
system.
+
This corresponds to the ``application`` 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.
@@ -357,7 +379,7 @@ async def update_application(
sent along with the request as metadata.
Returns:
- ~.gct_application.Application:
+ google.cloud.talent_v4beta1.types.Application:
Resource that represents a job
application record of a candidate.
@@ -376,7 +398,6 @@ async def update_application(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if application is not None:
request.application = application
@@ -414,7 +435,7 @@ async def delete_application(
r"""Deletes specified application.
Args:
- request (:class:`~.application_service.DeleteApplicationRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.DeleteApplicationRequest`):
The request object. Request to delete a application.
name (:class:`str`):
Required. The resource name of the application to be
@@ -424,10 +445,10 @@ async def delete_application(
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}/applications/{application_id}".
For example,
"projects/foo/tenants/bar/profiles/baz/applications/qux".
+
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.
@@ -448,7 +469,6 @@ async def delete_application(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -461,8 +481,10 @@ async def delete_application(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -491,7 +513,7 @@ async def list_applications(
r"""Lists all applications associated with the profile.
Args:
- request (:class:`~.application_service.ListApplicationsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.ListApplicationsRequest`):
The request object. List applications for which the
client has ACL visibility.
parent (:class:`str`):
@@ -501,10 +523,10 @@ async def list_applications(
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}",
for example, "projects/foo/tenants/bar/profiles/baz".
+
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.
@@ -512,7 +534,7 @@ async def list_applications(
sent along with the request as metadata.
Returns:
- ~.pagers.ListApplicationsAsyncPager:
+ google.cloud.talent_v4beta1.services.application_service.pagers.ListApplicationsAsyncPager:
The List applications response
object.
Iterating over this object will yield
@@ -534,7 +556,6 @@ async def list_applications(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
@@ -547,8 +568,10 @@ async def list_applications(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
diff --git a/google/cloud/talent_v4beta1/services/application_service/client.py b/google/cloud/talent_v4beta1/services/application_service/client.py
index b8204de1..46d97a01 100644
--- a/google/cloud/talent_v4beta1/services/application_service/client.py
+++ b/google/cloud/talent_v4beta1/services/application_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -37,10 +35,9 @@
from google.cloud.talent_v4beta1.types import application as gct_application
from google.cloud.talent_v4beta1.types import application_service
from google.cloud.talent_v4beta1.types import common
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
from .transports.base import ApplicationServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import ApplicationServiceGrpcTransport
from .transports.grpc_asyncio import ApplicationServiceGrpcAsyncIOTransport
@@ -63,7 +60,7 @@ class ApplicationServiceClientMeta(type):
def get_transport_class(
cls, label: str = None,
) -> Type[ApplicationServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -88,7 +85,8 @@ class ApplicationServiceClient(metaclass=ApplicationServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -120,10 +118,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ ApplicationServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -132,7 +147,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ ApplicationServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -142,10 +157,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> ApplicationServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- ApplicationServiceTransport: The transport used by the client instance.
+ ApplicationServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@@ -153,14 +169,14 @@ def transport(self) -> ApplicationServiceTransport:
def application_path(
project: str, tenant: str, profile: str, application: str,
) -> str:
- """Return a fully-qualified application string."""
+ """Returns a fully-qualified application string."""
return "projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}".format(
project=project, tenant=tenant, profile=profile, application=application,
)
@staticmethod
def parse_application_path(path: str) -> Dict[str, str]:
- """Parse a application path into its component segments."""
+ """Parses a application path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/profiles/(?P.+?)/applications/(?P.+?)$",
path,
@@ -169,14 +185,14 @@ def parse_application_path(path: str) -> Dict[str, str]:
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -185,14 +201,14 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def job_path(project: str, tenant: str, job: str,) -> str:
- """Return a fully-qualified job string."""
+ """Returns a fully-qualified job string."""
return "projects/{project}/tenants/{tenant}/jobs/{job}".format(
project=project, tenant=tenant, job=job,
)
@staticmethod
def parse_job_path(path: str) -> Dict[str, str]:
- """Parse a job path into its component segments."""
+ """Parses a job path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/jobs/(?P.+?)$",
path,
@@ -201,14 +217,14 @@ def parse_job_path(path: str) -> Dict[str, str]:
@staticmethod
def profile_path(project: str, tenant: str, profile: str,) -> str:
- """Return a fully-qualified profile string."""
+ """Returns a fully-qualified profile string."""
return "projects/{project}/tenants/{tenant}/profiles/{profile}".format(
project=project, tenant=tenant, profile=profile,
)
@staticmethod
def parse_profile_path(path: str) -> Dict[str, str]:
- """Parse a profile path into its component segments."""
+ """Parses a profile path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/profiles/(?P.+?)$",
path,
@@ -217,7 +233,7 @@ def parse_profile_path(path: str) -> Dict[str, str]:
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -230,7 +246,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -241,7 +257,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -252,7 +268,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -263,7 +279,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -277,12 +293,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, ApplicationServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the application service client.
+ """Instantiates the application service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -290,10 +306,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.ApplicationServiceTransport]): The
+ transport (Union[str, ApplicationServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -329,21 +345,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -355,12 +368,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -375,8 +390,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -386,7 +401,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -404,26 +419,27 @@ def create_application(
r"""Creates a new application entity.
Args:
- request (:class:`~.application_service.CreateApplicationRequest`):
+ request (google.cloud.talent_v4beta1.types.CreateApplicationRequest):
The request object. The Request of the CreateApplication
method.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the profile under which the
application is created.
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
For example, "projects/foo/tenants/bar/profiles/baz".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- application (:class:`~.gct_application.Application`):
+ application (google.cloud.talent_v4beta1.types.Application):
Required. The application to be
created.
+
This corresponds to the ``application`` 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.
@@ -431,7 +447,7 @@ def create_application(
sent along with the request as metadata.
Returns:
- ~.gct_application.Application:
+ google.cloud.talent_v4beta1.types.Application:
Resource that represents a job
application record of a candidate.
@@ -452,10 +468,8 @@ def create_application(
# there are no flattened fields.
if not isinstance(request, application_service.CreateApplicationRequest):
request = application_service.CreateApplicationRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if application is not None:
@@ -489,10 +503,10 @@ def get_application(
r"""Retrieves specified application.
Args:
- request (:class:`~.application_service.GetApplicationRequest`):
+ request (google.cloud.talent_v4beta1.types.GetApplicationRequest):
The request object. Request for getting a application by
name.
- name (:class:`str`):
+ name (str):
Required. The resource name of the application to be
retrieved.
@@ -500,10 +514,10 @@ def get_application(
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}/applications/{application_id}".
For example,
"projects/foo/tenants/bar/profiles/baz/applications/qux".
+
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.
@@ -511,7 +525,7 @@ def get_application(
sent along with the request as metadata.
Returns:
- ~.application.Application:
+ google.cloud.talent_v4beta1.types.Application:
Resource that represents a job
application record of a candidate.
@@ -532,10 +546,8 @@ def get_application(
# there are no flattened fields.
if not isinstance(request, application_service.GetApplicationRequest):
request = application_service.GetApplicationRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -567,17 +579,17 @@ def update_application(
r"""Updates specified application.
Args:
- request (:class:`~.application_service.UpdateApplicationRequest`):
+ request (google.cloud.talent_v4beta1.types.UpdateApplicationRequest):
The request object. Request for updating a specified
application.
- application (:class:`~.gct_application.Application`):
+ application (google.cloud.talent_v4beta1.types.Application):
Required. The application resource to
replace the current resource in the
system.
+
This corresponds to the ``application`` 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.
@@ -585,7 +597,7 @@ def update_application(
sent along with the request as metadata.
Returns:
- ~.gct_application.Application:
+ google.cloud.talent_v4beta1.types.Application:
Resource that represents a job
application record of a candidate.
@@ -606,10 +618,8 @@ def update_application(
# there are no flattened fields.
if not isinstance(request, application_service.UpdateApplicationRequest):
request = application_service.UpdateApplicationRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if application is not None:
request.application = application
@@ -643,9 +653,9 @@ def delete_application(
r"""Deletes specified application.
Args:
- request (:class:`~.application_service.DeleteApplicationRequest`):
+ request (google.cloud.talent_v4beta1.types.DeleteApplicationRequest):
The request object. Request to delete a application.
- name (:class:`str`):
+ name (str):
Required. The resource name of the application to be
deleted.
@@ -653,10 +663,10 @@ def delete_application(
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}/applications/{application_id}".
For example,
"projects/foo/tenants/bar/profiles/baz/applications/qux".
+
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.
@@ -679,10 +689,8 @@ def delete_application(
# there are no flattened fields.
if not isinstance(request, application_service.DeleteApplicationRequest):
request = application_service.DeleteApplicationRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -713,20 +721,20 @@ def list_applications(
r"""Lists all applications associated with the profile.
Args:
- request (:class:`~.application_service.ListApplicationsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListApplicationsRequest):
The request object. List applications for which the
client has ACL visibility.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the profile under which the
application is created.
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}",
for example, "projects/foo/tenants/bar/profiles/baz".
+
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.
@@ -734,7 +742,7 @@ def list_applications(
sent along with the request as metadata.
Returns:
- ~.pagers.ListApplicationsPager:
+ google.cloud.talent_v4beta1.services.application_service.pagers.ListApplicationsPager:
The List applications response
object.
Iterating over this object will yield
@@ -758,10 +766,8 @@ def list_applications(
# there are no flattened fields.
if not isinstance(request, application_service.ListApplicationsRequest):
request = application_service.ListApplicationsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
diff --git a/google/cloud/talent_v4beta1/services/application_service/pagers.py b/google/cloud/talent_v4beta1/services/application_service/pagers.py
index 0525dae8..877ae740 100644
--- a/google/cloud/talent_v4beta1/services/application_service/pagers.py
+++ b/google/cloud/talent_v4beta1/services/application_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4beta1.types import application
from google.cloud.talent_v4beta1.types import application_service
@@ -25,7 +32,7 @@ class ListApplicationsPager:
"""A pager for iterating through ``list_applications`` requests.
This class thinly wraps an initial
- :class:`~.application_service.ListApplicationsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListApplicationsResponse` object, and
provides an ``__iter__`` method to iterate through its
``applications`` field.
@@ -34,7 +41,7 @@ class ListApplicationsPager:
through the ``applications`` field on the
corresponding responses.
- All the usual :class:`~.application_service.ListApplicationsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListApplicationsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -52,9 +59,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.application_service.ListApplicationsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListApplicationsRequest):
The initial request object.
- response (:class:`~.application_service.ListApplicationsResponse`):
+ response (google.cloud.talent_v4beta1.types.ListApplicationsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -87,7 +94,7 @@ class ListApplicationsAsyncPager:
"""A pager for iterating through ``list_applications`` requests.
This class thinly wraps an initial
- :class:`~.application_service.ListApplicationsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListApplicationsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``applications`` field.
@@ -96,7 +103,7 @@ class ListApplicationsAsyncPager:
through the ``applications`` field on the
corresponding responses.
- All the usual :class:`~.application_service.ListApplicationsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListApplicationsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -109,14 +116,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.application_service.ListApplicationsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListApplicationsRequest):
The initial request object.
- response (:class:`~.application_service.ListApplicationsResponse`):
+ response (google.cloud.talent_v4beta1.types.ListApplicationsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4beta1/services/application_service/transports/__init__.py b/google/cloud/talent_v4beta1/services/application_service/transports/__init__.py
index b8633539..a8429e5c 100644
--- a/google/cloud/talent_v4beta1/services/application_service/transports/__init__.py
+++ b/google/cloud/talent_v4beta1/services/application_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4beta1/services/application_service/transports/base.py b/google/cloud/talent_v4beta1/services/application_service/transports/base.py
index 83ba6405..b4cf38f7 100644
--- a/google/cloud/talent_v4beta1/services/application_service/transports/base.py
+++ b/google/cloud/talent_v4beta1/services/application_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import application
from google.cloud.talent_v4beta1.types import application as gct_application
from google.cloud.talent_v4beta1.types import application_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -38,6 +38,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class ApplicationServiceTransport(abc.ABC):
"""Abstract transport class for ApplicationService."""
@@ -47,21 +56,25 @@ class ApplicationServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -70,42 +83,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -120,8 +168,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -136,8 +186,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -149,8 +201,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -160,53 +214,47 @@ def _prep_wrapped_messages(self, client_info):
@property
def create_application(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[application_service.CreateApplicationRequest],
- typing.Union[
- gct_application.Application, typing.Awaitable[gct_application.Application]
- ],
+ Union[gct_application.Application, Awaitable[gct_application.Application]],
]:
raise NotImplementedError()
@property
def get_application(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[application_service.GetApplicationRequest],
- typing.Union[
- application.Application, typing.Awaitable[application.Application]
- ],
+ Union[application.Application, Awaitable[application.Application]],
]:
raise NotImplementedError()
@property
def update_application(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[application_service.UpdateApplicationRequest],
- typing.Union[
- gct_application.Application, typing.Awaitable[gct_application.Application]
- ],
+ Union[gct_application.Application, Awaitable[gct_application.Application]],
]:
raise NotImplementedError()
@property
def delete_application(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[application_service.DeleteApplicationRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_applications(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[application_service.ListApplicationsRequest],
- typing.Union[
+ Union[
application_service.ListApplicationsResponse,
- typing.Awaitable[application_service.ListApplicationsResponse],
+ Awaitable[application_service.ListApplicationsResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py b/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py
index 07e17b28..1d2b753d 100644
--- a/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py
+++ b/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -29,8 +27,7 @@
from google.cloud.talent_v4beta1.types import application
from google.cloud.talent_v4beta1.types import application as gct_application
from google.cloud.talent_v4beta1.types import application_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import ApplicationServiceTransport, DEFAULT_CLIENT_INFO
@@ -54,20 +51,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -91,6 +91,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -98,6 +102,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -105,72 +111,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -178,23 +173,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -202,7 +188,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -225,13 +211,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -326,7 +314,7 @@ def update_application(
@property
def delete_application(
self,
- ) -> Callable[[application_service.DeleteApplicationRequest], empty.Empty]:
+ ) -> Callable[[application_service.DeleteApplicationRequest], empty_pb2.Empty]:
r"""Return a callable for the delete application method over gRPC.
Deletes specified application.
@@ -345,7 +333,7 @@ def delete_application(
self._stubs["delete_application"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.ApplicationService/DeleteApplication",
request_serializer=application_service.DeleteApplicationRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_application"]
diff --git a/google/cloud/talent_v4beta1/services/application_service/transports/grpc_asyncio.py b/google/cloud/talent_v4beta1/services/application_service/transports/grpc_asyncio.py
index 0727f683..9601825e 100644
--- a/google/cloud/talent_v4beta1/services/application_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4beta1/services/application_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -30,8 +28,7 @@
from google.cloud.talent_v4beta1.types import application
from google.cloud.talent_v4beta1.types import application as gct_application
from google.cloud.talent_v4beta1.types import application_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import ApplicationServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import ApplicationServiceGrpcTransport
@@ -57,7 +54,7 @@ class ApplicationServiceGrpcAsyncIOTransport(ApplicationServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -65,7 +62,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -84,13 +81,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -98,20 +97,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -136,13 +138,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -150,72 +158,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -223,17 +219,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -335,7 +322,7 @@ def update_application(
def delete_application(
self,
) -> Callable[
- [application_service.DeleteApplicationRequest], Awaitable[empty.Empty]
+ [application_service.DeleteApplicationRequest], Awaitable[empty_pb2.Empty]
]:
r"""Return a callable for the delete application method over gRPC.
@@ -355,7 +342,7 @@ def delete_application(
self._stubs["delete_application"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.ApplicationService/DeleteApplication",
request_serializer=application_service.DeleteApplicationRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_application"]
diff --git a/google/cloud/talent_v4beta1/services/company_service/__init__.py b/google/cloud/talent_v4beta1/services/company_service/__init__.py
index a7154172..6849b6f3 100644
--- a/google/cloud/talent_v4beta1/services/company_service/__init__.py
+++ b/google/cloud/talent_v4beta1/services/company_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import CompanyServiceClient
from .async_client import CompanyServiceAsyncClient
diff --git a/google/cloud/talent_v4beta1/services/company_service/async_client.py b/google/cloud/talent_v4beta1/services/company_service/async_client.py
index 98c39a8e..8c87d66e 100644
--- a/google/cloud/talent_v4beta1/services/company_service/async_client.py
+++ b/google/cloud/talent_v4beta1/services/company_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,10 +20,10 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.services.company_service import pagers
@@ -33,7 +31,6 @@
from google.cloud.talent_v4beta1.types import company
from google.cloud.talent_v4beta1.types import company as gct_company
from google.cloud.talent_v4beta1.types import company_service
-
from .transports.base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import CompanyServiceGrpcAsyncIOTransport
from .client import CompanyServiceClient
@@ -51,42 +48,67 @@ class CompanyServiceAsyncClient:
company_path = staticmethod(CompanyServiceClient.company_path)
parse_company_path = staticmethod(CompanyServiceClient.parse_company_path)
-
common_billing_account_path = staticmethod(
CompanyServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
CompanyServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(CompanyServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(
CompanyServiceClient.parse_common_folder_path
)
-
common_organization_path = staticmethod(
CompanyServiceClient.common_organization_path
)
parse_common_organization_path = staticmethod(
CompanyServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(CompanyServiceClient.common_project_path)
parse_common_project_path = staticmethod(
CompanyServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(CompanyServiceClient.common_location_path)
parse_common_location_path = staticmethod(
CompanyServiceClient.parse_common_location_path
)
- from_service_account_file = CompanyServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompanyServiceAsyncClient: The constructed client.
+ """
+ return CompanyServiceClient.from_service_account_info.__func__(CompanyServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompanyServiceAsyncClient: The constructed client.
+ """
+ return CompanyServiceClient.from_service_account_file.__func__(CompanyServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> CompanyServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
CompanyServiceTransport: The transport used by the client instance.
@@ -100,12 +122,12 @@ def transport(self) -> CompanyServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, CompanyServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the company service client.
+ """Instantiates the company service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -137,7 +159,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = CompanyServiceClient(
credentials=credentials,
transport=transport,
@@ -158,7 +179,7 @@ async def create_company(
r"""Creates a new company entity.
Args:
- request (:class:`~.company_service.CreateCompanyRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.CreateCompanyRequest`):
The request object. The Request of the CreateCompany
method.
parent (:class:`str`):
@@ -170,15 +191,15 @@ async def create_company(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created, for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- company (:class:`~.gct_company.Company`):
+ company (:class:`google.cloud.talent_v4beta1.types.Company`):
Required. The company to be created.
This corresponds to the ``company`` 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.
@@ -186,7 +207,7 @@ async def create_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4beta1.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -209,7 +230,6 @@ async def create_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if company is not None:
@@ -247,7 +267,7 @@ async def get_company(
r"""Retrieves specified company.
Args:
- request (:class:`~.company_service.GetCompanyRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.GetCompanyRequest`):
The request object. Request for getting a company by
name.
name (:class:`str`):
@@ -261,10 +281,10 @@ async def get_company(
If tenant id is unspecified, the default tenant is used,
for example, "projects/api-test-project/companies/bar".
+
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.
@@ -272,7 +292,7 @@ async def get_company(
sent along with the request as metadata.
Returns:
- ~.company.Company:
+ google.cloud.talent_v4beta1.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -295,7 +315,6 @@ async def get_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -308,8 +327,10 @@ async def get_company(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -339,17 +360,17 @@ async def update_company(
r"""Updates specified company.
Args:
- request (:class:`~.company_service.UpdateCompanyRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.UpdateCompanyRequest`):
The request object. Request for updating a specified
company.
- company (:class:`~.gct_company.Company`):
+ company (:class:`google.cloud.talent_v4beta1.types.Company`):
Required. The company resource to
replace the current resource in the
system.
+
This corresponds to the ``company`` 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.
@@ -357,7 +378,7 @@ async def update_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4beta1.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -380,7 +401,6 @@ async def update_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if company is not None:
request.company = company
@@ -420,7 +440,7 @@ async def delete_company(
it.
Args:
- request (:class:`~.company_service.DeleteCompanyRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.DeleteCompanyRequest`):
The request object. Request to delete a company.
name (:class:`str`):
Required. The resource name of the company to be
@@ -432,10 +452,10 @@ async def delete_company(
If tenant id is unspecified, the default tenant is used,
for example, "projects/foo/companies/bar".
+
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.
@@ -456,7 +476,6 @@ async def delete_company(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -469,8 +488,10 @@ async def delete_company(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -499,7 +520,7 @@ async def list_companies(
r"""Lists all companies associated with the project.
Args:
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.ListCompaniesRequest`):
The request object. List companies for which the client
has ACL visibility.
parent (:class:`str`):
@@ -512,10 +533,10 @@ async def list_companies(
If tenant id is unspecified, the default tenant will be
used, for example, "projects/foo".
+
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.
@@ -523,7 +544,7 @@ async def list_companies(
sent along with the request as metadata.
Returns:
- ~.pagers.ListCompaniesAsyncPager:
+ google.cloud.talent_v4beta1.services.company_service.pagers.ListCompaniesAsyncPager:
The List companies response object.
Iterating over this object will yield
results and resolve additional pages
@@ -544,7 +565,6 @@ async def list_companies(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
@@ -557,8 +577,10 @@ async def list_companies(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
diff --git a/google/cloud/talent_v4beta1/services/company_service/client.py b/google/cloud/talent_v4beta1/services/company_service/client.py
index e4638852..865cb90b 100644
--- a/google/cloud/talent_v4beta1/services/company_service/client.py
+++ b/google/cloud/talent_v4beta1/services/company_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -37,7 +35,6 @@
from google.cloud.talent_v4beta1.types import company
from google.cloud.talent_v4beta1.types import company as gct_company
from google.cloud.talent_v4beta1.types import company_service
-
from .transports.base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import CompanyServiceGrpcTransport
from .transports.grpc_asyncio import CompanyServiceGrpcAsyncIOTransport
@@ -58,7 +55,7 @@ class CompanyServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = CompanyServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[CompanyServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -83,7 +80,8 @@ class CompanyServiceClient(metaclass=CompanyServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -115,10 +113,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompanyServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -127,7 +142,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ CompanyServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -137,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> CompanyServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- CompanyServiceTransport: The transport used by the client instance.
+ CompanyServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -162,7 +178,7 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -175,7 +191,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -186,7 +202,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -197,7 +213,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -208,7 +224,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -222,12 +238,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, CompanyServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the company service client.
+ """Instantiates the company service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -235,10 +251,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.CompanyServiceTransport]): The
+ transport (Union[str, CompanyServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -274,21 +290,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -300,12 +313,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -320,8 +335,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -331,7 +346,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -349,10 +364,10 @@ def create_company(
r"""Creates a new company entity.
Args:
- request (:class:`~.company_service.CreateCompanyRequest`):
+ request (google.cloud.talent_v4beta1.types.CreateCompanyRequest):
The request object. The Request of the CreateCompany
method.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the tenant under which the
company is created.
@@ -361,15 +376,15 @@ def create_company(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created, for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- company (:class:`~.gct_company.Company`):
+ company (google.cloud.talent_v4beta1.types.Company):
Required. The company to be created.
This corresponds to the ``company`` 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.
@@ -377,7 +392,7 @@ def create_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4beta1.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -402,10 +417,8 @@ def create_company(
# there are no flattened fields.
if not isinstance(request, company_service.CreateCompanyRequest):
request = company_service.CreateCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if company is not None:
@@ -439,10 +452,10 @@ def get_company(
r"""Retrieves specified company.
Args:
- request (:class:`~.company_service.GetCompanyRequest`):
+ request (google.cloud.talent_v4beta1.types.GetCompanyRequest):
The request object. Request for getting a company by
name.
- name (:class:`str`):
+ name (str):
Required. The resource name of the company to be
retrieved.
@@ -453,10 +466,10 @@ def get_company(
If tenant id is unspecified, the default tenant is used,
for example, "projects/api-test-project/companies/bar".
+
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.
@@ -464,7 +477,7 @@ def get_company(
sent along with the request as metadata.
Returns:
- ~.company.Company:
+ google.cloud.talent_v4beta1.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -489,10 +502,8 @@ def get_company(
# there are no flattened fields.
if not isinstance(request, company_service.GetCompanyRequest):
request = company_service.GetCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -524,17 +535,17 @@ def update_company(
r"""Updates specified company.
Args:
- request (:class:`~.company_service.UpdateCompanyRequest`):
+ request (google.cloud.talent_v4beta1.types.UpdateCompanyRequest):
The request object. Request for updating a specified
company.
- company (:class:`~.gct_company.Company`):
+ company (google.cloud.talent_v4beta1.types.Company):
Required. The company resource to
replace the current resource in the
system.
+
This corresponds to the ``company`` 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.
@@ -542,7 +553,7 @@ def update_company(
sent along with the request as metadata.
Returns:
- ~.gct_company.Company:
+ google.cloud.talent_v4beta1.types.Company:
A Company resource represents a
company in the service. A company is the
entity that owns job postings, that is,
@@ -567,10 +578,8 @@ def update_company(
# there are no flattened fields.
if not isinstance(request, company_service.UpdateCompanyRequest):
request = company_service.UpdateCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if company is not None:
request.company = company
@@ -606,9 +615,9 @@ def delete_company(
it.
Args:
- request (:class:`~.company_service.DeleteCompanyRequest`):
+ request (google.cloud.talent_v4beta1.types.DeleteCompanyRequest):
The request object. Request to delete a company.
- name (:class:`str`):
+ name (str):
Required. The resource name of the company to be
deleted.
@@ -618,10 +627,10 @@ def delete_company(
If tenant id is unspecified, the default tenant is used,
for example, "projects/foo/companies/bar".
+
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.
@@ -644,10 +653,8 @@ def delete_company(
# there are no flattened fields.
if not isinstance(request, company_service.DeleteCompanyRequest):
request = company_service.DeleteCompanyRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -678,10 +685,10 @@ def list_companies(
r"""Lists all companies associated with the project.
Args:
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (google.cloud.talent_v4beta1.types.ListCompaniesRequest):
The request object. List companies for which the client
has ACL visibility.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the tenant under which the
company is created.
@@ -691,10 +698,10 @@ def list_companies(
If tenant id is unspecified, the default tenant will be
used, for example, "projects/foo".
+
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.
@@ -702,7 +709,7 @@ def list_companies(
sent along with the request as metadata.
Returns:
- ~.pagers.ListCompaniesPager:
+ google.cloud.talent_v4beta1.services.company_service.pagers.ListCompaniesPager:
The List companies response object.
Iterating over this object will yield
results and resolve additional pages
@@ -725,10 +732,8 @@ def list_companies(
# there are no flattened fields.
if not isinstance(request, company_service.ListCompaniesRequest):
request = company_service.ListCompaniesRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
diff --git a/google/cloud/talent_v4beta1/services/company_service/pagers.py b/google/cloud/talent_v4beta1/services/company_service/pagers.py
index 6b25c9a9..55856dee 100644
--- a/google/cloud/talent_v4beta1/services/company_service/pagers.py
+++ b/google/cloud/talent_v4beta1/services/company_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4beta1.types import company
from google.cloud.talent_v4beta1.types import company_service
@@ -25,7 +32,7 @@ class ListCompaniesPager:
"""A pager for iterating through ``list_companies`` requests.
This class thinly wraps an initial
- :class:`~.company_service.ListCompaniesResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListCompaniesResponse` object, and
provides an ``__iter__`` method to iterate through its
``companies`` field.
@@ -34,7 +41,7 @@ class ListCompaniesPager:
through the ``companies`` field on the
corresponding responses.
- All the usual :class:`~.company_service.ListCompaniesResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListCompaniesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -52,9 +59,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (google.cloud.talent_v4beta1.types.ListCompaniesRequest):
The initial request object.
- response (:class:`~.company_service.ListCompaniesResponse`):
+ response (google.cloud.talent_v4beta1.types.ListCompaniesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -87,7 +94,7 @@ class ListCompaniesAsyncPager:
"""A pager for iterating through ``list_companies`` requests.
This class thinly wraps an initial
- :class:`~.company_service.ListCompaniesResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListCompaniesResponse` object, and
provides an ``__aiter__`` method to iterate through its
``companies`` field.
@@ -96,7 +103,7 @@ class ListCompaniesAsyncPager:
through the ``companies`` field on the
corresponding responses.
- All the usual :class:`~.company_service.ListCompaniesResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListCompaniesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -109,14 +116,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.company_service.ListCompaniesRequest`):
+ request (google.cloud.talent_v4beta1.types.ListCompaniesRequest):
The initial request object.
- response (:class:`~.company_service.ListCompaniesResponse`):
+ response (google.cloud.talent_v4beta1.types.ListCompaniesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4beta1/services/company_service/transports/__init__.py b/google/cloud/talent_v4beta1/services/company_service/transports/__init__.py
index 51e34763..e8b8e830 100644
--- a/google/cloud/talent_v4beta1/services/company_service/transports/__init__.py
+++ b/google/cloud/talent_v4beta1/services/company_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4beta1/services/company_service/transports/base.py b/google/cloud/talent_v4beta1/services/company_service/transports/base.py
index 39fb541b..787483fc 100644
--- a/google/cloud/talent_v4beta1/services/company_service/transports/base.py
+++ b/google/cloud/talent_v4beta1/services/company_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import company
from google.cloud.talent_v4beta1.types import company as gct_company
from google.cloud.talent_v4beta1.types import company_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -38,6 +38,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class CompanyServiceTransport(abc.ABC):
"""Abstract transport class for CompanyService."""
@@ -47,21 +56,25 @@ class CompanyServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -70,42 +83,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -120,8 +168,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -136,8 +186,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -149,8 +201,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -160,47 +214,47 @@ def _prep_wrapped_messages(self, client_info):
@property
def create_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.CreateCompanyRequest],
- typing.Union[gct_company.Company, typing.Awaitable[gct_company.Company]],
+ Union[gct_company.Company, Awaitable[gct_company.Company]],
]:
raise NotImplementedError()
@property
def get_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.GetCompanyRequest],
- typing.Union[company.Company, typing.Awaitable[company.Company]],
+ Union[company.Company, Awaitable[company.Company]],
]:
raise NotImplementedError()
@property
def update_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.UpdateCompanyRequest],
- typing.Union[gct_company.Company, typing.Awaitable[gct_company.Company]],
+ Union[gct_company.Company, Awaitable[gct_company.Company]],
]:
raise NotImplementedError()
@property
def delete_company(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.DeleteCompanyRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_companies(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[company_service.ListCompaniesRequest],
- typing.Union[
+ Union[
company_service.ListCompaniesResponse,
- typing.Awaitable[company_service.ListCompaniesResponse],
+ Awaitable[company_service.ListCompaniesResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py b/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py
index 4c833246..ef3cb4db 100644
--- a/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py
+++ b/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -29,8 +27,7 @@
from google.cloud.talent_v4beta1.types import company
from google.cloud.talent_v4beta1.types import company as gct_company
from google.cloud.talent_v4beta1.types import company_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
@@ -54,20 +51,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -91,6 +91,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -98,6 +102,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -105,72 +111,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -178,23 +173,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -202,7 +188,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -225,13 +211,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -322,7 +310,7 @@ def update_company(
@property
def delete_company(
self,
- ) -> Callable[[company_service.DeleteCompanyRequest], empty.Empty]:
+ ) -> Callable[[company_service.DeleteCompanyRequest], empty_pb2.Empty]:
r"""Return a callable for the delete company method over gRPC.
Deletes specified company.
@@ -343,7 +331,7 @@ def delete_company(
self._stubs["delete_company"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.CompanyService/DeleteCompany",
request_serializer=company_service.DeleteCompanyRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_company"]
diff --git a/google/cloud/talent_v4beta1/services/company_service/transports/grpc_asyncio.py b/google/cloud/talent_v4beta1/services/company_service/transports/grpc_asyncio.py
index 79a1d5fd..32721d7b 100644
--- a/google/cloud/talent_v4beta1/services/company_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4beta1/services/company_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -30,8 +28,7 @@
from google.cloud.talent_v4beta1.types import company
from google.cloud.talent_v4beta1.types import company as gct_company
from google.cloud.talent_v4beta1.types import company_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import CompanyServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import CompanyServiceGrpcTransport
@@ -57,7 +54,7 @@ class CompanyServiceGrpcAsyncIOTransport(CompanyServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -65,7 +62,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -84,13 +81,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -98,20 +97,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -136,13 +138,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -150,72 +158,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -223,17 +219,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -330,7 +317,7 @@ def update_company(
@property
def delete_company(
self,
- ) -> Callable[[company_service.DeleteCompanyRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[company_service.DeleteCompanyRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the delete company method over gRPC.
Deletes specified company.
@@ -351,7 +338,7 @@ def delete_company(
self._stubs["delete_company"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.CompanyService/DeleteCompany",
request_serializer=company_service.DeleteCompanyRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_company"]
diff --git a/google/cloud/talent_v4beta1/services/completion/__init__.py b/google/cloud/talent_v4beta1/services/completion/__init__.py
index 0c274210..fb544ebc 100644
--- a/google/cloud/talent_v4beta1/services/completion/__init__.py
+++ b/google/cloud/talent_v4beta1/services/completion/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import CompletionClient
from .async_client import CompletionAsyncClient
diff --git a/google/cloud/talent_v4beta1/services/completion/async_client.py b/google/cloud/talent_v4beta1/services/completion/async_client.py
index 40da92eb..7a113dd4 100644
--- a/google/cloud/talent_v4beta1/services/completion/async_client.py
+++ b/google/cloud/talent_v4beta1/services/completion/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,15 +20,14 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import completion_service
-
from .transports.base import CompletionTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import CompletionGrpcAsyncIOTransport
from .client import CompletionClient
@@ -46,36 +43,61 @@ class CompletionAsyncClient:
company_path = staticmethod(CompletionClient.company_path)
parse_company_path = staticmethod(CompletionClient.parse_company_path)
-
common_billing_account_path = staticmethod(
CompletionClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
CompletionClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(CompletionClient.common_folder_path)
parse_common_folder_path = staticmethod(CompletionClient.parse_common_folder_path)
-
common_organization_path = staticmethod(CompletionClient.common_organization_path)
parse_common_organization_path = staticmethod(
CompletionClient.parse_common_organization_path
)
-
common_project_path = staticmethod(CompletionClient.common_project_path)
parse_common_project_path = staticmethod(CompletionClient.parse_common_project_path)
-
common_location_path = staticmethod(CompletionClient.common_location_path)
parse_common_location_path = staticmethod(
CompletionClient.parse_common_location_path
)
- from_service_account_file = CompletionClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompletionAsyncClient: The constructed client.
+ """
+ return CompletionClient.from_service_account_info.__func__(CompletionAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompletionAsyncClient: The constructed client.
+ """
+ return CompletionClient.from_service_account_file.__func__(CompletionAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> CompletionTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
CompletionTransport: The transport used by the client instance.
@@ -89,12 +111,12 @@ def transport(self) -> CompletionTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, CompletionTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the completion client.
+ """Instantiates the completion client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -126,7 +148,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = CompletionClient(
credentials=credentials,
transport=transport,
@@ -147,9 +168,8 @@ async def complete_query(
complete search box.
Args:
- request (:class:`~.completion_service.CompleteQueryRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.CompleteQueryRequest`):
The request object. Auto-complete parameters.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -157,11 +177,10 @@ async def complete_query(
sent along with the request as metadata.
Returns:
- ~.completion_service.CompleteQueryResponse:
+ google.cloud.talent_v4beta1.types.CompleteQueryResponse:
Response of auto-complete query.
"""
# Create or coerce a protobuf request object.
-
request = completion_service.CompleteQueryRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
@@ -173,8 +192,10 @@ async def complete_query(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
diff --git a/google/cloud/talent_v4beta1/services/completion/client.py b/google/cloud/talent_v4beta1/services/completion/client.py
index f01febaf..c5a6f8e8 100644
--- a/google/cloud/talent_v4beta1/services/completion/client.py
+++ b/google/cloud/talent_v4beta1/services/completion/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -34,7 +32,6 @@
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import completion_service
-
from .transports.base import CompletionTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import CompletionGrpcTransport
from .transports.grpc_asyncio import CompletionGrpcAsyncIOTransport
@@ -53,7 +50,7 @@ class CompletionClientMeta(type):
_transport_registry["grpc_asyncio"] = CompletionGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[CompletionTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -76,7 +73,8 @@ class CompletionClient(metaclass=CompletionClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -108,10 +106,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ CompletionClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -120,7 +135,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ CompletionClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -130,23 +145,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> CompletionTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- CompletionTransport: The transport used by the client instance.
+ CompletionTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -155,7 +171,7 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -168,7 +184,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -179,7 +195,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -190,7 +206,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -201,7 +217,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -215,12 +231,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, CompletionTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the completion client.
+ """Instantiates the completion client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -228,10 +244,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.CompletionTransport]): The
+ transport (Union[str, CompletionTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -267,21 +283,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -293,12 +306,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -313,8 +328,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -324,7 +339,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -342,9 +357,8 @@ def complete_query(
complete search box.
Args:
- request (:class:`~.completion_service.CompleteQueryRequest`):
+ request (google.cloud.talent_v4beta1.types.CompleteQueryRequest):
The request object. Auto-complete parameters.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -352,11 +366,10 @@ def complete_query(
sent along with the request as metadata.
Returns:
- ~.completion_service.CompleteQueryResponse:
+ google.cloud.talent_v4beta1.types.CompleteQueryResponse:
Response of auto-complete query.
"""
# Create or coerce a protobuf request object.
-
# Minor optimization to avoid making a copy if the user passes
# in a completion_service.CompleteQueryRequest.
# There's no risk of modifying the input as we've already verified
diff --git a/google/cloud/talent_v4beta1/services/completion/transports/__init__.py b/google/cloud/talent_v4beta1/services/completion/transports/__init__.py
index df284f3e..01ea0e8d 100644
--- a/google/cloud/talent_v4beta1/services/completion/transports/__init__.py
+++ b/google/cloud/talent_v4beta1/services/completion/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4beta1/services/completion/transports/base.py b/google/cloud/talent_v4beta1/services/completion/transports/base.py
index 95e41990..77969b7a 100644
--- a/google/cloud/talent_v4beta1/services/completion/transports/base.py
+++ b/google/cloud/talent_v4beta1/services/completion/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,20 +13,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import completion_service
-
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution("google-cloud-talent",).version,
@@ -35,6 +35,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class CompletionTransport(abc.ABC):
"""Abstract transport class for Completion."""
@@ -44,21 +53,25 @@ class CompletionTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -67,42 +80,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -114,8 +162,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -125,11 +175,11 @@ def _prep_wrapped_messages(self, client_info):
@property
def complete_query(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[completion_service.CompleteQueryRequest],
- typing.Union[
+ Union[
completion_service.CompleteQueryResponse,
- typing.Awaitable[completion_service.CompleteQueryResponse],
+ Awaitable[completion_service.CompleteQueryResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py
index 086da12a..4f416c44 100644
--- a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py
+++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,20 +13,18 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.cloud.talent_v4beta1.types import completion_service
-
from .base import CompletionTransport, DEFAULT_CLIENT_INFO
@@ -50,20 +47,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -87,6 +87,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -94,6 +98,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -101,72 +107,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -174,23 +169,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -198,7 +184,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -221,13 +207,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
diff --git a/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py b/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py
index fa49dda0..98af1d8f 100644
--- a/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,21 +13,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
from google.cloud.talent_v4beta1.types import completion_service
-
from .base import CompletionTransport, DEFAULT_CLIENT_INFO
from .grpc import CompletionGrpcTransport
@@ -53,7 +50,7 @@ class CompletionGrpcAsyncIOTransport(CompletionTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -61,7 +58,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -80,13 +77,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -94,20 +93,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -132,13 +134,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -146,72 +154,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -219,17 +215,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
diff --git a/google/cloud/talent_v4beta1/services/event_service/__init__.py b/google/cloud/talent_v4beta1/services/event_service/__init__.py
index f321845c..d58ce120 100644
--- a/google/cloud/talent_v4beta1/services/event_service/__init__.py
+++ b/google/cloud/talent_v4beta1/services/event_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import EventServiceClient
from .async_client import EventServiceAsyncClient
diff --git a/google/cloud/talent_v4beta1/services/event_service/async_client.py b/google/cloud/talent_v4beta1/services/event_service/async_client.py
index 553aed17..9144f664 100644
--- a/google/cloud/talent_v4beta1/services/event_service/async_client.py
+++ b/google/cloud/talent_v4beta1/services/event_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,16 +20,15 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import event
from google.cloud.talent_v4beta1.types import event_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import EventServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import EventServiceGrpcAsyncIOTransport
from .client import EventServiceClient
@@ -47,38 +44,63 @@ class EventServiceAsyncClient:
company_path = staticmethod(EventServiceClient.company_path)
parse_company_path = staticmethod(EventServiceClient.parse_company_path)
-
common_billing_account_path = staticmethod(
EventServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
EventServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(EventServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(EventServiceClient.parse_common_folder_path)
-
common_organization_path = staticmethod(EventServiceClient.common_organization_path)
parse_common_organization_path = staticmethod(
EventServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(EventServiceClient.common_project_path)
parse_common_project_path = staticmethod(
EventServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(EventServiceClient.common_location_path)
parse_common_location_path = staticmethod(
EventServiceClient.parse_common_location_path
)
- from_service_account_file = EventServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ EventServiceAsyncClient: The constructed client.
+ """
+ return EventServiceClient.from_service_account_info.__func__(EventServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ EventServiceAsyncClient: The constructed client.
+ """
+ return EventServiceClient.from_service_account_file.__func__(EventServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> EventServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
EventServiceTransport: The transport used by the client instance.
@@ -92,12 +114,12 @@ def transport(self) -> EventServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, EventServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the event service client.
+ """Instantiates the event service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -129,7 +151,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = EventServiceClient(
credentials=credentials,
transport=transport,
@@ -156,7 +177,7 @@ async def create_client_event(
about self service tools.
Args:
- request (:class:`~.event_service.CreateClientEventRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.CreateClientEventRequest`):
The request object. The report event request.
parent (:class:`str`):
Required. Resource name of the tenant under which the
@@ -167,17 +188,18 @@ async def create_client_event(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created, for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- client_event (:class:`~.event.ClientEvent`):
+ client_event (:class:`google.cloud.talent_v4beta1.types.ClientEvent`):
Required. Events issued when end user
interacts with customer's application
that uses Cloud Talent Solution.
+
This corresponds to the ``client_event`` 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.
@@ -185,7 +207,7 @@ async def create_client_event(
sent along with the request as metadata.
Returns:
- ~.event.ClientEvent:
+ google.cloud.talent_v4beta1.types.ClientEvent:
An event issued when an end user
interacts with the application that
implements Cloud Talent Solution.
@@ -212,7 +234,6 @@ async def create_client_event(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if client_event is not None:
diff --git a/google/cloud/talent_v4beta1/services/event_service/client.py b/google/cloud/talent_v4beta1/services/event_service/client.py
index 21204729..fcbdce3d 100644
--- a/google/cloud/talent_v4beta1/services/event_service/client.py
+++ b/google/cloud/talent_v4beta1/services/event_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -34,8 +32,7 @@
from google.cloud.talent_v4beta1.types import event
from google.cloud.talent_v4beta1.types import event_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import EventServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import EventServiceGrpcTransport
from .transports.grpc_asyncio import EventServiceGrpcAsyncIOTransport
@@ -54,7 +51,7 @@ class EventServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = EventServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[EventServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -77,7 +74,8 @@ class EventServiceClient(metaclass=EventServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -109,10 +107,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ EventServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -121,7 +136,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ EventServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -131,23 +146,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> EventServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- EventServiceTransport: The transport used by the client instance.
+ EventServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -156,7 +172,7 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -169,7 +185,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -180,7 +196,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -191,7 +207,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -202,7 +218,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -216,12 +232,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, EventServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the event service client.
+ """Instantiates the event service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -229,10 +245,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.EventServiceTransport]): The
+ transport (Union[str, EventServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -268,21 +284,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -294,12 +307,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -314,8 +329,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -325,7 +340,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -349,9 +364,9 @@ def create_client_event(
about self service tools.
Args:
- request (:class:`~.event_service.CreateClientEventRequest`):
+ request (google.cloud.talent_v4beta1.types.CreateClientEventRequest):
The request object. The report event request.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the tenant under which the
event is created.
@@ -360,17 +375,18 @@ def create_client_event(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created, for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- client_event (:class:`~.event.ClientEvent`):
+ client_event (google.cloud.talent_v4beta1.types.ClientEvent):
Required. Events issued when end user
interacts with customer's application
that uses Cloud Talent Solution.
+
This corresponds to the ``client_event`` 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.
@@ -378,7 +394,7 @@ def create_client_event(
sent along with the request as metadata.
Returns:
- ~.event.ClientEvent:
+ google.cloud.talent_v4beta1.types.ClientEvent:
An event issued when an end user
interacts with the application that
implements Cloud Talent Solution.
@@ -407,10 +423,8 @@ def create_client_event(
# there are no flattened fields.
if not isinstance(request, event_service.CreateClientEventRequest):
request = event_service.CreateClientEventRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if client_event is not None:
diff --git a/google/cloud/talent_v4beta1/services/event_service/transports/__init__.py b/google/cloud/talent_v4beta1/services/event_service/transports/__init__.py
index c7dabde5..200c7dae 100644
--- a/google/cloud/talent_v4beta1/services/event_service/transports/__init__.py
+++ b/google/cloud/talent_v4beta1/services/event_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4beta1/services/event_service/transports/base.py b/google/cloud/talent_v4beta1/services/event_service/transports/base.py
index cd643c9d..95e666ac 100644
--- a/google/cloud/talent_v4beta1/services/event_service/transports/base.py
+++ b/google/cloud/talent_v4beta1/services/event_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,21 +13,22 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import event
from google.cloud.talent_v4beta1.types import event_service
-
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution("google-cloud-talent",).version,
@@ -36,6 +36,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class EventServiceTransport(abc.ABC):
"""Abstract transport class for EventService."""
@@ -45,21 +54,25 @@ class EventServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -68,42 +81,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -116,9 +164,9 @@ def _prep_wrapped_messages(self, client_info):
@property
def create_client_event(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[event_service.CreateClientEventRequest],
- typing.Union[event.ClientEvent, typing.Awaitable[event.ClientEvent]],
+ Union[event.ClientEvent, Awaitable[event.ClientEvent]],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py b/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py
index 5b8edccd..f8cc600f 100644
--- a/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py
+++ b/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,21 +13,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.cloud.talent_v4beta1.types import event
from google.cloud.talent_v4beta1.types import event_service
-
from .base import EventServiceTransport, DEFAULT_CLIENT_INFO
@@ -51,20 +48,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -88,6 +88,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -95,6 +99,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -102,72 +108,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -175,23 +170,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -199,7 +185,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -222,13 +208,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
diff --git a/google/cloud/talent_v4beta1/services/event_service/transports/grpc_asyncio.py b/google/cloud/talent_v4beta1/services/event_service/transports/grpc_asyncio.py
index 6a4cbe75..797cbde3 100644
--- a/google/cloud/talent_v4beta1/services/event_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4beta1/services/event_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,20 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
from google.cloud.talent_v4beta1.types import event
from google.cloud.talent_v4beta1.types import event_service
-
from .base import EventServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import EventServiceGrpcTransport
@@ -54,7 +51,7 @@ class EventServiceGrpcAsyncIOTransport(EventServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -62,7 +59,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -81,13 +78,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -95,20 +94,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -133,13 +135,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -147,72 +155,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- # 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
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -220,17 +216,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
diff --git a/google/cloud/talent_v4beta1/services/job_service/__init__.py b/google/cloud/talent_v4beta1/services/job_service/__init__.py
index 5f157047..3d8d94db 100644
--- a/google/cloud/talent_v4beta1/services/job_service/__init__.py
+++ b/google/cloud/talent_v4beta1/services/job_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import JobServiceClient
from .async_client import JobServiceAsyncClient
diff --git a/google/cloud/talent_v4beta1/services/job_service/async_client.py b/google/cloud/talent_v4beta1/services/job_service/async_client.py
index a5ad40c6..12e1dc9e 100644
--- a/google/cloud/talent_v4beta1/services/job_service/async_client.py
+++ b/google/cloud/talent_v4beta1/services/job_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,10 +20,10 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.api_core import operation # type: ignore
@@ -35,8 +33,7 @@
from google.cloud.talent_v4beta1.types import job
from google.cloud.talent_v4beta1.types import job as gct_job
from google.cloud.talent_v4beta1.types import job_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import JobServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import JobServiceGrpcAsyncIOTransport
from .client import JobServiceClient
@@ -56,36 +53,61 @@ class JobServiceAsyncClient:
parse_company_path = staticmethod(JobServiceClient.parse_company_path)
job_path = staticmethod(JobServiceClient.job_path)
parse_job_path = staticmethod(JobServiceClient.parse_job_path)
-
common_billing_account_path = staticmethod(
JobServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
JobServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(JobServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(JobServiceClient.parse_common_folder_path)
-
common_organization_path = staticmethod(JobServiceClient.common_organization_path)
parse_common_organization_path = staticmethod(
JobServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(JobServiceClient.common_project_path)
parse_common_project_path = staticmethod(JobServiceClient.parse_common_project_path)
-
common_location_path = staticmethod(JobServiceClient.common_location_path)
parse_common_location_path = staticmethod(
JobServiceClient.parse_common_location_path
)
- from_service_account_file = JobServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ JobServiceAsyncClient: The constructed client.
+ """
+ return JobServiceClient.from_service_account_info.__func__(JobServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ JobServiceAsyncClient: The constructed client.
+ """
+ return JobServiceClient.from_service_account_file.__func__(JobServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> JobServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
JobServiceTransport: The transport used by the client instance.
@@ -99,12 +121,12 @@ def transport(self) -> JobServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, JobServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the job service client.
+ """Instantiates the job service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -136,7 +158,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = JobServiceClient(
credentials=credentials,
transport=transport,
@@ -159,7 +180,7 @@ async def create_job(
but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.CreateJobRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.CreateJobRequest`):
The request object. Create job request.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -170,15 +191,15 @@ async def create_job(
example, "projects/foo/tenant/bar". If tenant id is
unspecified a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- job (:class:`~.gct_job.Job`):
+ job (:class:`google.cloud.talent_v4beta1.types.Job`):
Required. The Job to be created.
This corresponds to the ``job`` 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.
@@ -186,12 +207,11 @@ async def create_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a
- [Company][google.cloud.talent.v4beta1.Company], which is
- the hiring entity responsible for the job.
+ google.cloud.talent_v4beta1.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4beta1.Company], which
+ is the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -208,7 +228,6 @@ async def create_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if job is not None:
@@ -247,7 +266,7 @@ async def batch_create_jobs(
r"""Begins executing a batch create jobs operation.
Args:
- request (:class:`~.job_service.BatchCreateJobsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.BatchCreateJobsRequest`):
The request object. Request to create a batch of jobs.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -258,15 +277,15 @@ async def batch_create_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (:class:`Sequence[google.cloud.talent_v4beta1.types.Job]`):
Required. The jobs to be created.
This corresponds to the ``jobs`` 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.
@@ -274,18 +293,14 @@ async def batch_create_jobs(
sent along with the request as metadata.
Returns:
- ~.operation_async.AsyncOperation:
+ google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.JobOperationResult``: The result
- of
- [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs]
- or
- [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
- APIs. It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4beta1.types.JobOperationResult` The result of [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs] or
+ [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
+ APIs. It's used to replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -302,10 +317,8 @@ async def batch_create_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
if jobs:
request.jobs.extend(jobs)
@@ -350,7 +363,7 @@ async def get_job(
recently EXPIRED within the last 90 days.
Args:
- request (:class:`~.job_service.GetJobRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.GetJobRequest`):
The request object. Get job request.
name (:class:`str`):
Required. The resource name of the job to retrieve.
@@ -361,10 +374,10 @@ async def get_job(
If tenant id is unspecified, the default tenant is used.
For example, "projects/foo/jobs/bar".
+
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.
@@ -372,12 +385,11 @@ async def get_job(
sent along with the request as metadata.
Returns:
- ~.job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a
- [Company][google.cloud.talent.v4beta1.Company], which is
- the hiring entity responsible for the job.
+ google.cloud.talent_v4beta1.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4beta1.Company], which
+ is the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -394,7 +406,6 @@ async def get_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -407,8 +418,10 @@ async def get_job(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -441,14 +454,13 @@ async def update_job(
minutes.
Args:
- request (:class:`~.job_service.UpdateJobRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.UpdateJobRequest`):
The request object. Update job request.
- job (:class:`~.gct_job.Job`):
+ job (:class:`google.cloud.talent_v4beta1.types.Job`):
Required. The Job to be updated.
This corresponds to the ``job`` 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.
@@ -456,12 +468,11 @@ async def update_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a
- [Company][google.cloud.talent.v4beta1.Company], which is
- the hiring entity responsible for the job.
+ google.cloud.talent_v4beta1.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4beta1.Company], which
+ is the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -478,7 +489,6 @@ async def update_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if job is not None:
request.job = job
@@ -515,7 +525,7 @@ async def batch_update_jobs(
r"""Begins executing a batch update jobs operation.
Args:
- request (:class:`~.job_service.BatchUpdateJobsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.BatchUpdateJobsRequest`):
The request object. Request to update a batch of jobs.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -526,15 +536,15 @@ async def batch_update_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (:class:`Sequence[google.cloud.talent_v4beta1.types.Job]`):
Required. The jobs to be updated.
This corresponds to the ``jobs`` 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.
@@ -542,18 +552,14 @@ async def batch_update_jobs(
sent along with the request as metadata.
Returns:
- ~.operation_async.AsyncOperation:
+ google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.JobOperationResult``: The result
- of
- [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs]
- or
- [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
- APIs. It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4beta1.types.JobOperationResult` The result of [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs] or
+ [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
+ APIs. It's used to replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -570,10 +576,8 @@ async def batch_update_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
if jobs:
request.jobs.extend(jobs)
@@ -619,7 +623,7 @@ async def delete_job(
seconds, but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.DeleteJobRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.DeleteJobRequest`):
The request object. Delete job request.
name (:class:`str`):
Required. The resource name of the job to be deleted.
@@ -630,10 +634,10 @@ async def delete_job(
If tenant id is unspecified, the default tenant is used.
For example, "projects/foo/jobs/bar".
+
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.
@@ -654,7 +658,6 @@ async def delete_job(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -667,8 +670,10 @@ async def delete_job(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -699,7 +704,7 @@ async def batch_delete_jobs(
filter.
Args:
- request (:class:`~.job_service.BatchDeleteJobsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.BatchDeleteJobsRequest`):
The request object. Batch delete jobs request.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -710,6 +715,7 @@ async def batch_delete_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -725,11 +731,11 @@ async def batch_delete_jobs(
- ``requisitionId`` (Required)
Sample Query: companyName = "projects/foo/companies/bar"
- AND requisitionId = "req-1".
+ AND requisitionId = "req-1"
+
This corresponds to the ``filter`` 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.
@@ -750,7 +756,6 @@ async def batch_delete_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if filter is not None:
@@ -788,7 +793,7 @@ async def list_jobs(
r"""Lists jobs by filter.
Args:
- request (:class:`~.job_service.ListJobsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.ListJobsRequest`):
The request object. List jobs request.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -799,6 +804,7 @@ async def list_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
@@ -824,11 +830,11 @@ async def list_jobs(
requisitionId = "req-1"
- companyName =
"projects/foo/tenants/bar/companies/baz" AND status =
- "EXPIRED".
+ "EXPIRED"
+
This corresponds to the ``filter`` 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.
@@ -836,7 +842,7 @@ async def list_jobs(
sent along with the request as metadata.
Returns:
- ~.pagers.ListJobsAsyncPager:
+ google.cloud.talent_v4beta1.services.job_service.pagers.ListJobsAsyncPager:
List jobs response.
Iterating over this object will yield
results and resolve additional pages
@@ -857,7 +863,6 @@ async def list_jobs(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if filter is not None:
@@ -872,8 +877,10 @@ async def list_jobs(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -914,10 +921,9 @@ async def search_jobs(
has permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.SearchJobsRequest`):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -925,7 +931,7 @@ async def search_jobs(
sent along with the request as metadata.
Returns:
- ~.pagers.SearchJobsAsyncPager:
+ google.cloud.talent_v4beta1.services.job_service.pagers.SearchJobsAsyncPager:
Response for SearchJob method.
Iterating over this object will yield
results and resolve additional pages
@@ -933,7 +939,6 @@ async def search_jobs(
"""
# Create or coerce a protobuf request object.
-
request = job_service.SearchJobsRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
@@ -985,10 +990,9 @@ async def search_jobs_for_alert(
permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.SearchJobsRequest`):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -996,7 +1000,7 @@ async def search_jobs_for_alert(
sent along with the request as metadata.
Returns:
- ~.pagers.SearchJobsForAlertAsyncPager:
+ google.cloud.talent_v4beta1.services.job_service.pagers.SearchJobsForAlertAsyncPager:
Response for SearchJob method.
Iterating over this object will yield
results and resolve additional pages
@@ -1004,7 +1008,6 @@ async def search_jobs_for_alert(
"""
# Create or coerce a protobuf request object.
-
request = job_service.SearchJobsRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
diff --git a/google/cloud/talent_v4beta1/services/job_service/client.py b/google/cloud/talent_v4beta1/services/job_service/client.py
index 726b75ae..91698a32 100644
--- a/google/cloud/talent_v4beta1/services/job_service/client.py
+++ b/google/cloud/talent_v4beta1/services/job_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -39,8 +37,7 @@
from google.cloud.talent_v4beta1.types import job
from google.cloud.talent_v4beta1.types import job as gct_job
from google.cloud.talent_v4beta1.types import job_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
from .transports.base import JobServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import JobServiceGrpcTransport
from .transports.grpc_asyncio import JobServiceGrpcAsyncIOTransport
@@ -59,7 +56,7 @@ class JobServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = JobServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[JobServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -84,7 +81,8 @@ class JobServiceClient(metaclass=JobServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -116,10 +114,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ JobServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -128,7 +143,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ JobServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -138,23 +153,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> JobServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- JobServiceTransport: The transport used by the client instance.
+ JobServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def company_path(project: str, tenant: str, company: str,) -> str:
- """Return a fully-qualified company string."""
+ """Returns a fully-qualified company string."""
return "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@staticmethod
def parse_company_path(path: str) -> Dict[str, str]:
- """Parse a company path into its component segments."""
+ """Parses a company path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/companies/(?P.+?)$",
path,
@@ -163,14 +179,14 @@ def parse_company_path(path: str) -> Dict[str, str]:
@staticmethod
def job_path(project: str, tenant: str, job: str,) -> str:
- """Return a fully-qualified job string."""
+ """Returns a fully-qualified job string."""
return "projects/{project}/tenants/{tenant}/jobs/{job}".format(
project=project, tenant=tenant, job=job,
)
@staticmethod
def parse_job_path(path: str) -> Dict[str, str]:
- """Parse a job path into its component segments."""
+ """Parses a job path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/jobs/(?P.+?)$",
path,
@@ -179,7 +195,7 @@ def parse_job_path(path: str) -> Dict[str, str]:
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -192,7 +208,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -203,7 +219,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -214,7 +230,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -225,7 +241,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -239,12 +255,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, JobServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the job service client.
+ """Instantiates the job service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -252,10 +268,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.JobServiceTransport]): The
+ transport (Union[str, JobServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -291,21 +307,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -317,12 +330,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -337,8 +352,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -348,7 +363,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -368,9 +383,9 @@ def create_job(
but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.CreateJobRequest`):
+ request (google.cloud.talent_v4beta1.types.CreateJobRequest):
The request object. Create job request.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
@@ -379,15 +394,15 @@ def create_job(
example, "projects/foo/tenant/bar". If tenant id is
unspecified a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- job (:class:`~.gct_job.Job`):
+ job (google.cloud.talent_v4beta1.types.Job):
Required. The Job to be created.
This corresponds to the ``job`` 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.
@@ -395,12 +410,11 @@ def create_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a
- [Company][google.cloud.talent.v4beta1.Company], which is
- the hiring entity responsible for the job.
+ google.cloud.talent_v4beta1.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4beta1.Company], which
+ is the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -419,10 +433,8 @@ def create_job(
# there are no flattened fields.
if not isinstance(request, job_service.CreateJobRequest):
request = job_service.CreateJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if job is not None:
@@ -457,9 +469,9 @@ def batch_create_jobs(
r"""Begins executing a batch create jobs operation.
Args:
- request (:class:`~.job_service.BatchCreateJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.BatchCreateJobsRequest):
The request object. Request to create a batch of jobs.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
@@ -468,15 +480,15 @@ def batch_create_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (Sequence[google.cloud.talent_v4beta1.types.Job]):
Required. The jobs to be created.
This corresponds to the ``jobs`` 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.
@@ -484,18 +496,14 @@ def batch_create_jobs(
sent along with the request as metadata.
Returns:
- ~.operation.Operation:
+ google.api_core.operation.Operation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.JobOperationResult``: The result
- of
- [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs]
- or
- [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
- APIs. It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4beta1.types.JobOperationResult` The result of [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs] or
+ [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
+ APIs. It's used to replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -514,15 +522,12 @@ def batch_create_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.BatchCreateJobsRequest):
request = job_service.BatchCreateJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
- if jobs:
- request.jobs.extend(jobs)
+ if jobs is not None:
+ request.jobs = jobs
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
@@ -561,9 +566,9 @@ def get_job(
recently EXPIRED within the last 90 days.
Args:
- request (:class:`~.job_service.GetJobRequest`):
+ request (google.cloud.talent_v4beta1.types.GetJobRequest):
The request object. Get job request.
- name (:class:`str`):
+ name (str):
Required. The resource name of the job to retrieve.
The format is
@@ -572,10 +577,10 @@ def get_job(
If tenant id is unspecified, the default tenant is used.
For example, "projects/foo/jobs/bar".
+
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.
@@ -583,12 +588,11 @@ def get_job(
sent along with the request as metadata.
Returns:
- ~.job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a
- [Company][google.cloud.talent.v4beta1.Company], which is
- the hiring entity responsible for the job.
+ google.cloud.talent_v4beta1.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4beta1.Company], which
+ is the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -607,10 +611,8 @@ def get_job(
# there are no flattened fields.
if not isinstance(request, job_service.GetJobRequest):
request = job_service.GetJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -645,14 +647,13 @@ def update_job(
minutes.
Args:
- request (:class:`~.job_service.UpdateJobRequest`):
+ request (google.cloud.talent_v4beta1.types.UpdateJobRequest):
The request object. Update job request.
- job (:class:`~.gct_job.Job`):
+ job (google.cloud.talent_v4beta1.types.Job):
Required. The Job to be updated.
This corresponds to the ``job`` 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.
@@ -660,12 +661,11 @@ def update_job(
sent along with the request as metadata.
Returns:
- ~.gct_job.Job:
- A Job resource represents a job posting (also referred
- to as a "job listing" or "job requisition"). A job
- belongs to a
- [Company][google.cloud.talent.v4beta1.Company], which is
- the hiring entity responsible for the job.
+ google.cloud.talent_v4beta1.types.Job:
+ A Job resource represents a job posting (also referred to as a "job listing"
+ or "job requisition"). A job belongs to a
+ [Company][google.cloud.talent.v4beta1.Company], which
+ is the hiring entity responsible for the job.
"""
# Create or coerce a protobuf request object.
@@ -684,10 +684,8 @@ def update_job(
# there are no flattened fields.
if not isinstance(request, job_service.UpdateJobRequest):
request = job_service.UpdateJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if job is not None:
request.job = job
@@ -720,9 +718,9 @@ def batch_update_jobs(
r"""Begins executing a batch update jobs operation.
Args:
- request (:class:`~.job_service.BatchUpdateJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.BatchUpdateJobsRequest):
The request object. Request to update a batch of jobs.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
@@ -731,15 +729,15 @@ def batch_update_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- jobs (:class:`Sequence[~.job.Job]`):
+ jobs (Sequence[google.cloud.talent_v4beta1.types.Job]):
Required. The jobs to be updated.
This corresponds to the ``jobs`` 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.
@@ -747,18 +745,14 @@ def batch_update_jobs(
sent along with the request as metadata.
Returns:
- ~.operation.Operation:
+ google.api_core.operation.Operation:
An object representing a long-running operation.
- The result type for the operation will be
- :class:``~.job_service.JobOperationResult``: The result
- of
- [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs]
- or
- [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
- APIs. It's used to replace
- [google.longrunning.Operation.response][google.longrunning.Operation.response]
- in case of success.
+ The result type for the operation will be :class:`google.cloud.talent_v4beta1.types.JobOperationResult` The result of [JobService.BatchCreateJobs][google.cloud.talent.v4beta1.JobService.BatchCreateJobs] or
+ [JobService.BatchUpdateJobs][google.cloud.talent.v4beta1.JobService.BatchUpdateJobs]
+ APIs. It's used to replace
+ [google.longrunning.Operation.response][google.longrunning.Operation.response]
+ in case of success.
"""
# Create or coerce a protobuf request object.
@@ -777,15 +771,12 @@ def batch_update_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.BatchUpdateJobsRequest):
request = job_service.BatchUpdateJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
-
- if jobs:
- request.jobs.extend(jobs)
+ if jobs is not None:
+ request.jobs = jobs
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
@@ -825,9 +816,9 @@ def delete_job(
seconds, but it may take up to 5 minutes.
Args:
- request (:class:`~.job_service.DeleteJobRequest`):
+ request (google.cloud.talent_v4beta1.types.DeleteJobRequest):
The request object. Delete job request.
- name (:class:`str`):
+ name (str):
Required. The resource name of the job to be deleted.
The format is
@@ -836,10 +827,10 @@ def delete_job(
If tenant id is unspecified, the default tenant is used.
For example, "projects/foo/jobs/bar".
+
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.
@@ -862,10 +853,8 @@ def delete_job(
# there are no flattened fields.
if not isinstance(request, job_service.DeleteJobRequest):
request = job_service.DeleteJobRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -898,9 +887,9 @@ def batch_delete_jobs(
filter.
Args:
- request (:class:`~.job_service.BatchDeleteJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.BatchDeleteJobsRequest):
The request object. Batch delete jobs request.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
@@ -909,10 +898,11 @@ def batch_delete_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- filter (:class:`str`):
+ filter (str):
Required. The filter string specifies the jobs to be
deleted.
@@ -924,11 +914,11 @@ def batch_delete_jobs(
- ``requisitionId`` (Required)
Sample Query: companyName = "projects/foo/companies/bar"
- AND requisitionId = "req-1".
+ AND requisitionId = "req-1"
+
This corresponds to the ``filter`` 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.
@@ -951,10 +941,8 @@ def batch_delete_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.BatchDeleteJobsRequest):
request = job_service.BatchDeleteJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if filter is not None:
@@ -988,9 +976,9 @@ def list_jobs(
r"""Lists jobs by filter.
Args:
- request (:class:`~.job_service.ListJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListJobsRequest):
The request object. List jobs request.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the job is created.
@@ -999,10 +987,11 @@ def list_jobs(
example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- filter (:class:`str`):
+ filter (str):
Required. The filter string specifies the jobs to be
enumerated.
@@ -1024,11 +1013,11 @@ def list_jobs(
requisitionId = "req-1"
- companyName =
"projects/foo/tenants/bar/companies/baz" AND status =
- "EXPIRED".
+ "EXPIRED"
+
This corresponds to the ``filter`` 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.
@@ -1036,7 +1025,7 @@ def list_jobs(
sent along with the request as metadata.
Returns:
- ~.pagers.ListJobsPager:
+ google.cloud.talent_v4beta1.services.job_service.pagers.ListJobsPager:
List jobs response.
Iterating over this object will yield
results and resolve additional pages
@@ -1059,10 +1048,8 @@ def list_jobs(
# there are no flattened fields.
if not isinstance(request, job_service.ListJobsRequest):
request = job_service.ListJobsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if filter is not None:
@@ -1107,10 +1094,9 @@ def search_jobs(
has permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchJobsRequest):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -1118,7 +1104,7 @@ def search_jobs(
sent along with the request as metadata.
Returns:
- ~.pagers.SearchJobsPager:
+ google.cloud.talent_v4beta1.services.job_service.pagers.SearchJobsPager:
Response for SearchJob method.
Iterating over this object will yield
results and resolve additional pages
@@ -1126,7 +1112,6 @@ def search_jobs(
"""
# Create or coerce a protobuf request object.
-
# Minor optimization to avoid making a copy if the user passes
# in a job_service.SearchJobsRequest.
# There's no risk of modifying the input as we've already verified
@@ -1179,10 +1164,9 @@ def search_jobs_for_alert(
permission to search against.
Args:
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchJobsRequest):
The request object. The Request body of the `SearchJobs`
call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -1190,7 +1174,7 @@ def search_jobs_for_alert(
sent along with the request as metadata.
Returns:
- ~.pagers.SearchJobsForAlertPager:
+ google.cloud.talent_v4beta1.services.job_service.pagers.SearchJobsForAlertPager:
Response for SearchJob method.
Iterating over this object will yield
results and resolve additional pages
@@ -1198,7 +1182,6 @@ def search_jobs_for_alert(
"""
# Create or coerce a protobuf request object.
-
# Minor optimization to avoid making a copy if the user passes
# in a job_service.SearchJobsRequest.
# There's no risk of modifying the input as we've already verified
diff --git a/google/cloud/talent_v4beta1/services/job_service/pagers.py b/google/cloud/talent_v4beta1/services/job_service/pagers.py
index fcefff46..5fc60b11 100644
--- a/google/cloud/talent_v4beta1/services/job_service/pagers.py
+++ b/google/cloud/talent_v4beta1/services/job_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4beta1.types import job
from google.cloud.talent_v4beta1.types import job_service
@@ -25,7 +32,7 @@ class ListJobsPager:
"""A pager for iterating through ``list_jobs`` requests.
This class thinly wraps an initial
- :class:`~.job_service.ListJobsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListJobsResponse` object, and
provides an ``__iter__`` method to iterate through its
``jobs`` field.
@@ -34,7 +41,7 @@ class ListJobsPager:
through the ``jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.ListJobsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -52,9 +59,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.ListJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListJobsRequest):
The initial request object.
- response (:class:`~.job_service.ListJobsResponse`):
+ response (google.cloud.talent_v4beta1.types.ListJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -87,7 +94,7 @@ class ListJobsAsyncPager:
"""A pager for iterating through ``list_jobs`` requests.
This class thinly wraps an initial
- :class:`~.job_service.ListJobsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListJobsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``jobs`` field.
@@ -96,7 +103,7 @@ class ListJobsAsyncPager:
through the ``jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.ListJobsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -109,14 +116,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.ListJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListJobsRequest):
The initial request object.
- response (:class:`~.job_service.ListJobsResponse`):
+ response (google.cloud.talent_v4beta1.types.ListJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -153,7 +160,7 @@ class SearchJobsPager:
"""A pager for iterating through ``search_jobs`` requests.
This class thinly wraps an initial
- :class:`~.job_service.SearchJobsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse` object, and
provides an ``__iter__`` method to iterate through its
``matching_jobs`` field.
@@ -162,7 +169,7 @@ class SearchJobsPager:
through the ``matching_jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.SearchJobsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -180,9 +187,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchJobsRequest):
The initial request object.
- response (:class:`~.job_service.SearchJobsResponse`):
+ response (google.cloud.talent_v4beta1.types.SearchJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -215,7 +222,7 @@ class SearchJobsAsyncPager:
"""A pager for iterating through ``search_jobs`` requests.
This class thinly wraps an initial
- :class:`~.job_service.SearchJobsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``matching_jobs`` field.
@@ -224,7 +231,7 @@ class SearchJobsAsyncPager:
through the ``matching_jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.SearchJobsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -237,14 +244,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchJobsRequest):
The initial request object.
- response (:class:`~.job_service.SearchJobsResponse`):
+ response (google.cloud.talent_v4beta1.types.SearchJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -281,7 +288,7 @@ class SearchJobsForAlertPager:
"""A pager for iterating through ``search_jobs_for_alert`` requests.
This class thinly wraps an initial
- :class:`~.job_service.SearchJobsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse` object, and
provides an ``__iter__`` method to iterate through its
``matching_jobs`` field.
@@ -290,7 +297,7 @@ class SearchJobsForAlertPager:
through the ``matching_jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.SearchJobsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -308,9 +315,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchJobsRequest):
The initial request object.
- response (:class:`~.job_service.SearchJobsResponse`):
+ response (google.cloud.talent_v4beta1.types.SearchJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -343,7 +350,7 @@ class SearchJobsForAlertAsyncPager:
"""A pager for iterating through ``search_jobs_for_alert`` requests.
This class thinly wraps an initial
- :class:`~.job_service.SearchJobsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``matching_jobs`` field.
@@ -352,7 +359,7 @@ class SearchJobsForAlertAsyncPager:
through the ``matching_jobs`` field on the
corresponding responses.
- All the usual :class:`~.job_service.SearchJobsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.SearchJobsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -365,14 +372,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.job_service.SearchJobsRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchJobsRequest):
The initial request object.
- response (:class:`~.job_service.SearchJobsResponse`):
+ response (google.cloud.talent_v4beta1.types.SearchJobsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4beta1/services/job_service/transports/__init__.py b/google/cloud/talent_v4beta1/services/job_service/transports/__init__.py
index 349bfbcd..c512946d 100644
--- a/google/cloud/talent_v4beta1/services/job_service/transports/__init__.py
+++ b/google/cloud/talent_v4beta1/services/job_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4beta1/services/job_service/transports/base.py b/google/cloud/talent_v4beta1/services/job_service/transports/base.py
index ffef5f17..687c85e8 100644
--- a/google/cloud/talent_v4beta1/services/job_service/transports/base.py
+++ b/google/cloud/talent_v4beta1/services/job_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,24 +13,25 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.api_core import operations_v1 # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import job
from google.cloud.talent_v4beta1.types import job as gct_job
from google.cloud.talent_v4beta1.types import job_service
-from google.longrunning import operations_pb2 as operations # type: ignore
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -40,6 +40,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class JobServiceTransport(abc.ABC):
"""Abstract transport class for JobService."""
@@ -49,21 +58,25 @@ class JobServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -72,42 +85,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -125,8 +173,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -144,8 +194,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -160,8 +212,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -184,84 +238,77 @@ def operations_client(self) -> operations_v1.OperationsClient:
@property
def create_job(
self,
- ) -> typing.Callable[
- [job_service.CreateJobRequest],
- typing.Union[gct_job.Job, typing.Awaitable[gct_job.Job]],
+ ) -> Callable[
+ [job_service.CreateJobRequest], Union[gct_job.Job, Awaitable[gct_job.Job]]
]:
raise NotImplementedError()
@property
def batch_create_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.BatchCreateJobsRequest],
- typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def get_job(
self,
- ) -> typing.Callable[
- [job_service.GetJobRequest], typing.Union[job.Job, typing.Awaitable[job.Job]]
- ]:
+ ) -> Callable[[job_service.GetJobRequest], Union[job.Job, Awaitable[job.Job]]]:
raise NotImplementedError()
@property
def update_job(
self,
- ) -> typing.Callable[
- [job_service.UpdateJobRequest],
- typing.Union[gct_job.Job, typing.Awaitable[gct_job.Job]],
+ ) -> Callable[
+ [job_service.UpdateJobRequest], Union[gct_job.Job, Awaitable[gct_job.Job]]
]:
raise NotImplementedError()
@property
def batch_update_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.BatchUpdateJobsRequest],
- typing.Union[operations.Operation, typing.Awaitable[operations.Operation]],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def delete_job(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.DeleteJobRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def batch_delete_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.BatchDeleteJobsRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.ListJobsRequest],
- typing.Union[
- job_service.ListJobsResponse, typing.Awaitable[job_service.ListJobsResponse]
- ],
+ Union[job_service.ListJobsResponse, Awaitable[job_service.ListJobsResponse]],
]:
raise NotImplementedError()
@property
def search_jobs(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.SearchJobsRequest],
- typing.Union[
- job_service.SearchJobsResponse,
- typing.Awaitable[job_service.SearchJobsResponse],
+ Union[
+ job_service.SearchJobsResponse, Awaitable[job_service.SearchJobsResponse]
],
]:
raise NotImplementedError()
@@ -269,11 +316,10 @@ def search_jobs(
@property
def search_jobs_for_alert(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[job_service.SearchJobsRequest],
- typing.Union[
- job_service.SearchJobsResponse,
- typing.Awaitable[job_service.SearchJobsResponse],
+ Union[
+ job_service.SearchJobsResponse, Awaitable[job_service.SearchJobsResponse]
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py b/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py
index c3526f6f..79503e45 100644
--- a/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py
+++ b/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -30,9 +28,8 @@
from google.cloud.talent_v4beta1.types import job
from google.cloud.talent_v4beta1.types import job as gct_job
from google.cloud.talent_v4beta1.types import job_service
-from google.longrunning import operations_pb2 as operations # type: ignore
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
from .base import JobServiceTransport, DEFAULT_CLIENT_INFO
@@ -56,20 +53,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -93,6 +93,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -100,6 +104,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -107,72 +113,62 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+ self._operations_client = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -180,24 +176,14 @@ def __init__(
],
)
- self._stubs = {} # type: Dict[str, Callable]
- self._operations_client = None
-
- # 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -205,7 +191,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -228,13 +214,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -287,7 +275,7 @@ def create_job(self) -> Callable[[job_service.CreateJobRequest], gct_job.Job]:
@property
def batch_create_jobs(
self,
- ) -> Callable[[job_service.BatchCreateJobsRequest], operations.Operation]:
+ ) -> Callable[[job_service.BatchCreateJobsRequest], operations_pb2.Operation]:
r"""Return a callable for the batch create jobs method over gRPC.
Begins executing a batch create jobs operation.
@@ -306,7 +294,7 @@ def batch_create_jobs(
self._stubs["batch_create_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/BatchCreateJobs",
request_serializer=job_service.BatchCreateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_create_jobs"]
@@ -365,7 +353,7 @@ def update_job(self) -> Callable[[job_service.UpdateJobRequest], gct_job.Job]:
@property
def batch_update_jobs(
self,
- ) -> Callable[[job_service.BatchUpdateJobsRequest], operations.Operation]:
+ ) -> Callable[[job_service.BatchUpdateJobsRequest], operations_pb2.Operation]:
r"""Return a callable for the batch update jobs method over gRPC.
Begins executing a batch update jobs operation.
@@ -384,12 +372,12 @@ def batch_update_jobs(
self._stubs["batch_update_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/BatchUpdateJobs",
request_serializer=job_service.BatchUpdateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_update_jobs"]
@property
- def delete_job(self) -> Callable[[job_service.DeleteJobRequest], empty.Empty]:
+ def delete_job(self) -> Callable[[job_service.DeleteJobRequest], empty_pb2.Empty]:
r"""Return a callable for the delete job method over gRPC.
Deletes the specified job.
@@ -410,14 +398,14 @@ def delete_job(self) -> Callable[[job_service.DeleteJobRequest], empty.Empty]:
self._stubs["delete_job"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/DeleteJob",
request_serializer=job_service.DeleteJobRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_job"]
@property
def batch_delete_jobs(
self,
- ) -> Callable[[job_service.BatchDeleteJobsRequest], empty.Empty]:
+ ) -> Callable[[job_service.BatchDeleteJobsRequest], empty_pb2.Empty]:
r"""Return a callable for the batch delete jobs method over gRPC.
Deletes a list of [Job][google.cloud.talent.v4beta1.Job]s by
@@ -437,7 +425,7 @@ def batch_delete_jobs(
self._stubs["batch_delete_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/BatchDeleteJobs",
request_serializer=job_service.BatchDeleteJobsRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["batch_delete_jobs"]
diff --git a/google/cloud/talent_v4beta1/services/job_service/transports/grpc_asyncio.py b/google/cloud/talent_v4beta1/services/job_service/transports/grpc_asyncio.py
index 794df7cf..5a391e79 100644
--- a/google/cloud/talent_v4beta1/services/job_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4beta1/services/job_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,16 +13,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
from google.api_core import operations_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -31,9 +29,8 @@
from google.cloud.talent_v4beta1.types import job
from google.cloud.talent_v4beta1.types import job as gct_job
from google.cloud.talent_v4beta1.types import job_service
-from google.longrunning import operations_pb2 as operations # type: ignore
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.longrunning import operations_pb2 # type: ignore
+from google.protobuf import empty_pb2 # type: ignore
from .base import JobServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import JobServiceGrpcTransport
@@ -59,7 +56,7 @@ class JobServiceGrpcAsyncIOTransport(JobServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -67,7 +64,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -86,13 +83,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -100,20 +99,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -138,13 +140,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -152,72 +160,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+ self._operations_client = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -225,18 +222,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
- self._operations_client = None
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -296,7 +283,7 @@ def create_job(
def batch_create_jobs(
self,
) -> Callable[
- [job_service.BatchCreateJobsRequest], Awaitable[operations.Operation]
+ [job_service.BatchCreateJobsRequest], Awaitable[operations_pb2.Operation]
]:
r"""Return a callable for the batch create jobs method over gRPC.
@@ -316,7 +303,7 @@ def batch_create_jobs(
self._stubs["batch_create_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/BatchCreateJobs",
request_serializer=job_service.BatchCreateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_create_jobs"]
@@ -378,7 +365,7 @@ def update_job(
def batch_update_jobs(
self,
) -> Callable[
- [job_service.BatchUpdateJobsRequest], Awaitable[operations.Operation]
+ [job_service.BatchUpdateJobsRequest], Awaitable[operations_pb2.Operation]
]:
r"""Return a callable for the batch update jobs method over gRPC.
@@ -398,14 +385,14 @@ def batch_update_jobs(
self._stubs["batch_update_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/BatchUpdateJobs",
request_serializer=job_service.BatchUpdateJobsRequest.serialize,
- response_deserializer=operations.Operation.FromString,
+ response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["batch_update_jobs"]
@property
def delete_job(
self,
- ) -> Callable[[job_service.DeleteJobRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[job_service.DeleteJobRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the delete job method over gRPC.
Deletes the specified job.
@@ -426,14 +413,14 @@ def delete_job(
self._stubs["delete_job"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/DeleteJob",
request_serializer=job_service.DeleteJobRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_job"]
@property
def batch_delete_jobs(
self,
- ) -> Callable[[job_service.BatchDeleteJobsRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[job_service.BatchDeleteJobsRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the batch delete jobs method over gRPC.
Deletes a list of [Job][google.cloud.talent.v4beta1.Job]s by
@@ -453,7 +440,7 @@ def batch_delete_jobs(
self._stubs["batch_delete_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.JobService/BatchDeleteJobs",
request_serializer=job_service.BatchDeleteJobsRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["batch_delete_jobs"]
diff --git a/google/cloud/talent_v4beta1/services/profile_service/__init__.py b/google/cloud/talent_v4beta1/services/profile_service/__init__.py
index bace920e..19b00dd9 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/__init__.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import ProfileServiceClient
from .async_client import ProfileServiceAsyncClient
diff --git a/google/cloud/talent_v4beta1/services/profile_service/async_client.py b/google/cloud/talent_v4beta1/services/profile_service/async_client.py
index 914e2bf4..286b6bd3 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/async_client.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,10 +20,10 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.services.profile_service import pagers
@@ -34,9 +32,8 @@
from google.cloud.talent_v4beta1.types import profile
from google.cloud.talent_v4beta1.types import profile as gct_profile
from google.cloud.talent_v4beta1.types import profile_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
from .transports.base import ProfileServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import ProfileServiceGrpcAsyncIOTransport
from .client import ProfileServiceClient
@@ -56,42 +53,67 @@ class ProfileServiceAsyncClient:
parse_profile_path = staticmethod(ProfileServiceClient.parse_profile_path)
tenant_path = staticmethod(ProfileServiceClient.tenant_path)
parse_tenant_path = staticmethod(ProfileServiceClient.parse_tenant_path)
-
common_billing_account_path = staticmethod(
ProfileServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
ProfileServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(ProfileServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(
ProfileServiceClient.parse_common_folder_path
)
-
common_organization_path = staticmethod(
ProfileServiceClient.common_organization_path
)
parse_common_organization_path = staticmethod(
ProfileServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(ProfileServiceClient.common_project_path)
parse_common_project_path = staticmethod(
ProfileServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(ProfileServiceClient.common_location_path)
parse_common_location_path = staticmethod(
ProfileServiceClient.parse_common_location_path
)
- from_service_account_file = ProfileServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ ProfileServiceAsyncClient: The constructed client.
+ """
+ return ProfileServiceClient.from_service_account_info.__func__(ProfileServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ ProfileServiceAsyncClient: The constructed client.
+ """
+ return ProfileServiceClient.from_service_account_file.__func__(ProfileServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> ProfileServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
ProfileServiceTransport: The transport used by the client instance.
@@ -105,12 +127,12 @@ def transport(self) -> ProfileServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, ProfileServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the profile service client.
+ """Instantiates the profile service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -142,7 +164,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = ProfileServiceClient(
credentials=credentials,
transport=transport,
@@ -162,7 +183,7 @@ async def list_profiles(
r"""Lists profiles by filter. The order is unspecified.
Args:
- request (:class:`~.profile_service.ListProfilesRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.ListProfilesRequest`):
The request object. List profiles request.
parent (:class:`str`):
Required. The resource name of the tenant under which
@@ -171,10 +192,10 @@ async def list_profiles(
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
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.
@@ -182,7 +203,7 @@ async def list_profiles(
sent along with the request as metadata.
Returns:
- ~.pagers.ListProfilesAsyncPager:
+ google.cloud.talent_v4beta1.services.profile_service.pagers.ListProfilesAsyncPager:
The List profiles response object.
Iterating over this object will yield
results and resolve additional pages
@@ -203,7 +224,6 @@ async def list_profiles(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
@@ -216,8 +236,10 @@ async def list_profiles(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -254,7 +276,7 @@ async def create_profile(
r"""Creates and returns a new profile.
Args:
- request (:class:`~.profile_service.CreateProfileRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.CreateProfileRequest`):
The request object. Create profile request.
parent (:class:`str`):
Required. The name of the tenant this profile belongs
@@ -263,15 +285,15 @@ async def create_profile(
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- profile (:class:`~.gct_profile.Profile`):
+ profile (:class:`google.cloud.talent_v4beta1.types.Profile`):
Required. The profile to be created.
This corresponds to the ``profile`` 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.
@@ -279,7 +301,7 @@ async def create_profile(
sent along with the request as metadata.
Returns:
- ~.gct_profile.Profile:
+ google.cloud.talent_v4beta1.types.Profile:
A resource that represents the
profile for a job candidate (also
referred to as a "single-source
@@ -300,7 +322,6 @@ async def create_profile(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if profile is not None:
@@ -338,7 +359,7 @@ async def get_profile(
r"""Gets the specified profile.
Args:
- request (:class:`~.profile_service.GetProfileRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.GetProfileRequest`):
The request object. Get profile request.
name (:class:`str`):
Required. Resource name of the profile to get.
@@ -346,10 +367,10 @@ async def get_profile(
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
For example, "projects/foo/tenants/bar/profiles/baz".
+
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.
@@ -357,7 +378,7 @@ async def get_profile(
sent along with the request as metadata.
Returns:
- ~.profile.Profile:
+ google.cloud.talent_v4beta1.types.Profile:
A resource that represents the
profile for a job candidate (also
referred to as a "single-source
@@ -378,7 +399,6 @@ async def get_profile(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -391,8 +411,10 @@ async def get_profile(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -423,14 +445,13 @@ async def update_profile(
result.
Args:
- request (:class:`~.profile_service.UpdateProfileRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.UpdateProfileRequest`):
The request object. Update profile request
- profile (:class:`~.gct_profile.Profile`):
+ profile (:class:`google.cloud.talent_v4beta1.types.Profile`):
Required. Profile to be updated.
This corresponds to the ``profile`` 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.
@@ -438,7 +459,7 @@ async def update_profile(
sent along with the request as metadata.
Returns:
- ~.gct_profile.Profile:
+ google.cloud.talent_v4beta1.types.Profile:
A resource that represents the
profile for a job candidate (also
referred to as a "single-source
@@ -459,7 +480,6 @@ async def update_profile(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if profile is not None:
request.profile = profile
@@ -499,7 +519,7 @@ async def delete_profile(
or assignments associated.
Args:
- request (:class:`~.profile_service.DeleteProfileRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.DeleteProfileRequest`):
The request object. Delete profile request.
name (:class:`str`):
Required. Resource name of the profile to be deleted.
@@ -507,10 +527,10 @@ async def delete_profile(
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
For example, "projects/foo/tenants/bar/profiles/baz".
+
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.
@@ -531,7 +551,6 @@ async def delete_profile(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -544,8 +563,10 @@ async def delete_profile(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -581,10 +602,9 @@ async def search_profiles(
for more information.
Args:
- request (:class:`~.profile_service.SearchProfilesRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.SearchProfilesRequest`):
The request object. The request body of the
`SearchProfiles` call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -592,7 +612,7 @@ async def search_profiles(
sent along with the request as metadata.
Returns:
- ~.pagers.SearchProfilesAsyncPager:
+ google.cloud.talent_v4beta1.services.profile_service.pagers.SearchProfilesAsyncPager:
Response of SearchProfiles method.
Iterating over this object will yield
results and resolve additional pages
@@ -600,7 +620,6 @@ async def search_profiles(
"""
# Create or coerce a protobuf request object.
-
request = profile_service.SearchProfilesRequest(request)
# Wrap the RPC method; this adds retry and timeout information,
diff --git a/google/cloud/talent_v4beta1/services/profile_service/client.py b/google/cloud/talent_v4beta1/services/profile_service/client.py
index 4cef4bba..8781fb53 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/client.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -38,9 +36,8 @@
from google.cloud.talent_v4beta1.types import profile
from google.cloud.talent_v4beta1.types import profile as gct_profile
from google.cloud.talent_v4beta1.types import profile_service
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
from .transports.base import ProfileServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import ProfileServiceGrpcTransport
from .transports.grpc_asyncio import ProfileServiceGrpcAsyncIOTransport
@@ -61,7 +58,7 @@ class ProfileServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = ProfileServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[ProfileServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -86,7 +83,8 @@ class ProfileServiceClient(metaclass=ProfileServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -118,10 +116,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ ProfileServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -130,7 +145,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ ProfileServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -140,23 +155,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> ProfileServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- ProfileServiceTransport: The transport used by the client instance.
+ ProfileServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def profile_path(project: str, tenant: str, profile: str,) -> str:
- """Return a fully-qualified profile string."""
+ """Returns a fully-qualified profile string."""
return "projects/{project}/tenants/{tenant}/profiles/{profile}".format(
project=project, tenant=tenant, profile=profile,
)
@staticmethod
def parse_profile_path(path: str) -> Dict[str, str]:
- """Parse a profile path into its component segments."""
+ """Parses a profile path into its component segments."""
m = re.match(
r"^projects/(?P.+?)/tenants/(?P.+?)/profiles/(?P.+?)$",
path,
@@ -165,20 +181,20 @@ def parse_profile_path(path: str) -> Dict[str, str]:
@staticmethod
def tenant_path(project: str, tenant: str,) -> str:
- """Return a fully-qualified tenant string."""
+ """Returns a fully-qualified tenant string."""
return "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@staticmethod
def parse_tenant_path(path: str) -> Dict[str, str]:
- """Parse a tenant path into its component segments."""
+ """Parses a tenant path into its component segments."""
m = re.match(r"^projects/(?P.+?)/tenants/(?P.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -191,7 +207,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -202,7 +218,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -213,7 +229,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -224,7 +240,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -238,12 +254,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, ProfileServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the profile service client.
+ """Instantiates the profile service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -251,10 +267,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.ProfileServiceTransport]): The
+ transport (Union[str, ProfileServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -290,21 +306,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -316,12 +329,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -336,8 +351,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -347,7 +362,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -364,19 +379,19 @@ def list_profiles(
r"""Lists profiles by filter. The order is unspecified.
Args:
- request (:class:`~.profile_service.ListProfilesRequest`):
+ request (google.cloud.talent_v4beta1.types.ListProfilesRequest):
The request object. List profiles request.
- parent (:class:`str`):
+ parent (str):
Required. The resource name of the tenant under which
the profile is created.
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
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.
@@ -384,7 +399,7 @@ def list_profiles(
sent along with the request as metadata.
Returns:
- ~.pagers.ListProfilesPager:
+ google.cloud.talent_v4beta1.services.profile_service.pagers.ListProfilesPager:
The List profiles response object.
Iterating over this object will yield
results and resolve additional pages
@@ -407,10 +422,8 @@ def list_profiles(
# there are no flattened fields.
if not isinstance(request, profile_service.ListProfilesRequest):
request = profile_service.ListProfilesRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
@@ -449,24 +462,24 @@ def create_profile(
r"""Creates and returns a new profile.
Args:
- request (:class:`~.profile_service.CreateProfileRequest`):
+ request (google.cloud.talent_v4beta1.types.CreateProfileRequest):
The request object. Create profile request.
- parent (:class:`str`):
+ parent (str):
Required. The name of the tenant this profile belongs
to.
The format is
"projects/{project_id}/tenants/{tenant_id}". For
example, "projects/foo/tenants/bar".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- profile (:class:`~.gct_profile.Profile`):
+ profile (google.cloud.talent_v4beta1.types.Profile):
Required. The profile to be created.
This corresponds to the ``profile`` 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.
@@ -474,7 +487,7 @@ def create_profile(
sent along with the request as metadata.
Returns:
- ~.gct_profile.Profile:
+ google.cloud.talent_v4beta1.types.Profile:
A resource that represents the
profile for a job candidate (also
referred to as a "single-source
@@ -497,10 +510,8 @@ def create_profile(
# there are no flattened fields.
if not isinstance(request, profile_service.CreateProfileRequest):
request = profile_service.CreateProfileRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if profile is not None:
@@ -534,18 +545,18 @@ def get_profile(
r"""Gets the specified profile.
Args:
- request (:class:`~.profile_service.GetProfileRequest`):
+ request (google.cloud.talent_v4beta1.types.GetProfileRequest):
The request object. Get profile request.
- name (:class:`str`):
+ name (str):
Required. Resource name of the profile to get.
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
For example, "projects/foo/tenants/bar/profiles/baz".
+
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.
@@ -553,7 +564,7 @@ def get_profile(
sent along with the request as metadata.
Returns:
- ~.profile.Profile:
+ google.cloud.talent_v4beta1.types.Profile:
A resource that represents the
profile for a job candidate (also
referred to as a "single-source
@@ -576,10 +587,8 @@ def get_profile(
# there are no flattened fields.
if not isinstance(request, profile_service.GetProfileRequest):
request = profile_service.GetProfileRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -612,14 +621,13 @@ def update_profile(
result.
Args:
- request (:class:`~.profile_service.UpdateProfileRequest`):
+ request (google.cloud.talent_v4beta1.types.UpdateProfileRequest):
The request object. Update profile request
- profile (:class:`~.gct_profile.Profile`):
+ profile (google.cloud.talent_v4beta1.types.Profile):
Required. Profile to be updated.
This corresponds to the ``profile`` 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.
@@ -627,7 +635,7 @@ def update_profile(
sent along with the request as metadata.
Returns:
- ~.gct_profile.Profile:
+ google.cloud.talent_v4beta1.types.Profile:
A resource that represents the
profile for a job candidate (also
referred to as a "single-source
@@ -650,10 +658,8 @@ def update_profile(
# there are no flattened fields.
if not isinstance(request, profile_service.UpdateProfileRequest):
request = profile_service.UpdateProfileRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if profile is not None:
request.profile = profile
@@ -689,18 +695,18 @@ def delete_profile(
or assignments associated.
Args:
- request (:class:`~.profile_service.DeleteProfileRequest`):
+ request (google.cloud.talent_v4beta1.types.DeleteProfileRequest):
The request object. Delete profile request.
- name (:class:`str`):
+ name (str):
Required. Resource name of the profile to be deleted.
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
For example, "projects/foo/tenants/bar/profiles/baz".
+
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.
@@ -723,10 +729,8 @@ def delete_profile(
# there are no flattened fields.
if not isinstance(request, profile_service.DeleteProfileRequest):
request = profile_service.DeleteProfileRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -764,10 +768,9 @@ def search_profiles(
for more information.
Args:
- request (:class:`~.profile_service.SearchProfilesRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchProfilesRequest):
The request object. The request body of the
`SearchProfiles` call.
-
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
@@ -775,7 +778,7 @@ def search_profiles(
sent along with the request as metadata.
Returns:
- ~.pagers.SearchProfilesPager:
+ google.cloud.talent_v4beta1.services.profile_service.pagers.SearchProfilesPager:
Response of SearchProfiles method.
Iterating over this object will yield
results and resolve additional pages
@@ -783,7 +786,6 @@ def search_profiles(
"""
# Create or coerce a protobuf request object.
-
# Minor optimization to avoid making a copy if the user passes
# in a profile_service.SearchProfilesRequest.
# There's no risk of modifying the input as we've already verified
diff --git a/google/cloud/talent_v4beta1/services/profile_service/pagers.py b/google/cloud/talent_v4beta1/services/profile_service/pagers.py
index c2f71326..0abb3c02 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/pagers.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4beta1.types import histogram
from google.cloud.talent_v4beta1.types import profile
@@ -26,7 +33,7 @@ class ListProfilesPager:
"""A pager for iterating through ``list_profiles`` requests.
This class thinly wraps an initial
- :class:`~.profile_service.ListProfilesResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListProfilesResponse` object, and
provides an ``__iter__`` method to iterate through its
``profiles`` field.
@@ -35,7 +42,7 @@ class ListProfilesPager:
through the ``profiles`` field on the
corresponding responses.
- All the usual :class:`~.profile_service.ListProfilesResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListProfilesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -53,9 +60,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.profile_service.ListProfilesRequest`):
+ request (google.cloud.talent_v4beta1.types.ListProfilesRequest):
The initial request object.
- response (:class:`~.profile_service.ListProfilesResponse`):
+ response (google.cloud.talent_v4beta1.types.ListProfilesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -88,7 +95,7 @@ class ListProfilesAsyncPager:
"""A pager for iterating through ``list_profiles`` requests.
This class thinly wraps an initial
- :class:`~.profile_service.ListProfilesResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListProfilesResponse` object, and
provides an ``__aiter__`` method to iterate through its
``profiles`` field.
@@ -97,7 +104,7 @@ class ListProfilesAsyncPager:
through the ``profiles`` field on the
corresponding responses.
- All the usual :class:`~.profile_service.ListProfilesResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListProfilesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -110,14 +117,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.profile_service.ListProfilesRequest`):
+ request (google.cloud.talent_v4beta1.types.ListProfilesRequest):
The initial request object.
- response (:class:`~.profile_service.ListProfilesResponse`):
+ response (google.cloud.talent_v4beta1.types.ListProfilesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -154,7 +161,7 @@ class SearchProfilesPager:
"""A pager for iterating through ``search_profiles`` requests.
This class thinly wraps an initial
- :class:`~.profile_service.SearchProfilesResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.SearchProfilesResponse` object, and
provides an ``__iter__`` method to iterate through its
``histogram_query_results`` field.
@@ -163,7 +170,7 @@ class SearchProfilesPager:
through the ``histogram_query_results`` field on the
corresponding responses.
- All the usual :class:`~.profile_service.SearchProfilesResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.SearchProfilesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -181,9 +188,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.profile_service.SearchProfilesRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchProfilesRequest):
The initial request object.
- response (:class:`~.profile_service.SearchProfilesResponse`):
+ response (google.cloud.talent_v4beta1.types.SearchProfilesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -216,7 +223,7 @@ class SearchProfilesAsyncPager:
"""A pager for iterating through ``search_profiles`` requests.
This class thinly wraps an initial
- :class:`~.profile_service.SearchProfilesResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.SearchProfilesResponse` object, and
provides an ``__aiter__`` method to iterate through its
``histogram_query_results`` field.
@@ -225,7 +232,7 @@ class SearchProfilesAsyncPager:
through the ``histogram_query_results`` field on the
corresponding responses.
- All the usual :class:`~.profile_service.SearchProfilesResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.SearchProfilesResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -238,14 +245,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.profile_service.SearchProfilesRequest`):
+ request (google.cloud.talent_v4beta1.types.SearchProfilesRequest):
The initial request object.
- response (:class:`~.profile_service.SearchProfilesResponse`):
+ response (google.cloud.talent_v4beta1.types.SearchProfilesResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4beta1/services/profile_service/transports/__init__.py b/google/cloud/talent_v4beta1/services/profile_service/transports/__init__.py
index 927f6ae0..c5d02d70 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/transports/__init__.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4beta1/services/profile_service/transports/base.py b/google/cloud/talent_v4beta1/services/profile_service/transports/base.py
index dbd36ea2..e444b27e 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/transports/base.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import profile
from google.cloud.talent_v4beta1.types import profile as gct_profile
from google.cloud.talent_v4beta1.types import profile_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -38,6 +38,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class ProfileServiceTransport(abc.ABC):
"""Abstract transport class for ProfileService."""
@@ -47,21 +56,25 @@ class ProfileServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -70,42 +83,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -117,8 +165,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -133,8 +183,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -149,8 +201,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -163,11 +217,11 @@ def _prep_wrapped_messages(self, client_info):
@property
def list_profiles(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[profile_service.ListProfilesRequest],
- typing.Union[
+ Union[
profile_service.ListProfilesResponse,
- typing.Awaitable[profile_service.ListProfilesResponse],
+ Awaitable[profile_service.ListProfilesResponse],
],
]:
raise NotImplementedError()
@@ -175,47 +229,47 @@ def list_profiles(
@property
def create_profile(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[profile_service.CreateProfileRequest],
- typing.Union[gct_profile.Profile, typing.Awaitable[gct_profile.Profile]],
+ Union[gct_profile.Profile, Awaitable[gct_profile.Profile]],
]:
raise NotImplementedError()
@property
def get_profile(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[profile_service.GetProfileRequest],
- typing.Union[profile.Profile, typing.Awaitable[profile.Profile]],
+ Union[profile.Profile, Awaitable[profile.Profile]],
]:
raise NotImplementedError()
@property
def update_profile(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[profile_service.UpdateProfileRequest],
- typing.Union[gct_profile.Profile, typing.Awaitable[gct_profile.Profile]],
+ Union[gct_profile.Profile, Awaitable[gct_profile.Profile]],
]:
raise NotImplementedError()
@property
def delete_profile(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[profile_service.DeleteProfileRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def search_profiles(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[profile_service.SearchProfilesRequest],
- typing.Union[
+ Union[
profile_service.SearchProfilesResponse,
- typing.Awaitable[profile_service.SearchProfilesResponse],
+ Awaitable[profile_service.SearchProfilesResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py b/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py
index a0a0da7e..1bc5089e 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -29,8 +27,7 @@
from google.cloud.talent_v4beta1.types import profile
from google.cloud.talent_v4beta1.types import profile as gct_profile
from google.cloud.talent_v4beta1.types import profile_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import ProfileServiceTransport, DEFAULT_CLIENT_INFO
@@ -54,20 +51,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -91,6 +91,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -98,6 +102,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -105,72 +111,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -178,23 +173,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -202,7 +188,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -225,13 +211,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -351,7 +339,7 @@ def update_profile(
@property
def delete_profile(
self,
- ) -> Callable[[profile_service.DeleteProfileRequest], empty.Empty]:
+ ) -> Callable[[profile_service.DeleteProfileRequest], empty_pb2.Empty]:
r"""Return a callable for the delete profile method over gRPC.
Deletes the specified profile.
@@ -372,7 +360,7 @@ def delete_profile(
self._stubs["delete_profile"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.ProfileService/DeleteProfile",
request_serializer=profile_service.DeleteProfileRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_profile"]
diff --git a/google/cloud/talent_v4beta1/services/profile_service/transports/grpc_asyncio.py b/google/cloud/talent_v4beta1/services/profile_service/transports/grpc_asyncio.py
index 6db1ab4b..d4eb0b6c 100644
--- a/google/cloud/talent_v4beta1/services/profile_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4beta1/services/profile_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -30,8 +28,7 @@
from google.cloud.talent_v4beta1.types import profile
from google.cloud.talent_v4beta1.types import profile as gct_profile
from google.cloud.talent_v4beta1.types import profile_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import ProfileServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import ProfileServiceGrpcTransport
@@ -57,7 +54,7 @@ class ProfileServiceGrpcAsyncIOTransport(ProfileServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -65,7 +62,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -84,13 +81,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -98,20 +97,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -136,13 +138,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -150,72 +158,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -223,17 +219,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -360,7 +347,7 @@ def update_profile(
@property
def delete_profile(
self,
- ) -> Callable[[profile_service.DeleteProfileRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[profile_service.DeleteProfileRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the delete profile method over gRPC.
Deletes the specified profile.
@@ -381,7 +368,7 @@ def delete_profile(
self._stubs["delete_profile"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.ProfileService/DeleteProfile",
request_serializer=profile_service.DeleteProfileRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_profile"]
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/__init__.py b/google/cloud/talent_v4beta1/services/tenant_service/__init__.py
index c3e2ad3b..7a508509 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/__init__.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from .client import TenantServiceClient
from .async_client import TenantServiceAsyncClient
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/async_client.py b/google/cloud/talent_v4beta1/services/tenant_service/async_client.py
index be6fce85..7055f8d3 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/async_client.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/async_client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
import functools
import re
@@ -22,17 +20,16 @@
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 exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.services.tenant_service import pagers
from google.cloud.talent_v4beta1.types import tenant
from google.cloud.talent_v4beta1.types import tenant as gct_tenant
from google.cloud.talent_v4beta1.types import tenant_service
-
from .transports.base import TenantServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import TenantServiceGrpcAsyncIOTransport
from .client import TenantServiceClient
@@ -50,42 +47,67 @@ class TenantServiceAsyncClient:
tenant_path = staticmethod(TenantServiceClient.tenant_path)
parse_tenant_path = staticmethod(TenantServiceClient.parse_tenant_path)
-
common_billing_account_path = staticmethod(
TenantServiceClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
TenantServiceClient.parse_common_billing_account_path
)
-
common_folder_path = staticmethod(TenantServiceClient.common_folder_path)
parse_common_folder_path = staticmethod(
TenantServiceClient.parse_common_folder_path
)
-
common_organization_path = staticmethod(
TenantServiceClient.common_organization_path
)
parse_common_organization_path = staticmethod(
TenantServiceClient.parse_common_organization_path
)
-
common_project_path = staticmethod(TenantServiceClient.common_project_path)
parse_common_project_path = staticmethod(
TenantServiceClient.parse_common_project_path
)
-
common_location_path = staticmethod(TenantServiceClient.common_location_path)
parse_common_location_path = staticmethod(
TenantServiceClient.parse_common_location_path
)
- from_service_account_file = TenantServiceClient.from_service_account_file
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ TenantServiceAsyncClient: The constructed client.
+ """
+ return TenantServiceClient.from_service_account_info.__func__(TenantServiceAsyncClient, info, *args, **kwargs) # type: ignore
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ TenantServiceAsyncClient: The constructed client.
+ """
+ return TenantServiceClient.from_service_account_file.__func__(TenantServiceAsyncClient, filename, *args, **kwargs) # type: ignore
+
from_service_account_json = from_service_account_file
@property
def transport(self) -> TenantServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
TenantServiceTransport: The transport used by the client instance.
@@ -99,12 +121,12 @@ def transport(self) -> TenantServiceTransport:
def __init__(
self,
*,
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
transport: Union[str, TenantServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the tenant service client.
+ """Instantiates the tenant service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -136,7 +158,6 @@ def __init__(
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
-
self._client = TenantServiceClient(
credentials=credentials,
transport=transport,
@@ -157,7 +178,7 @@ async def create_tenant(
r"""Creates a new tenant entity.
Args:
- request (:class:`~.tenant_service.CreateTenantRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.CreateTenantRequest`):
The request object. The Request of the CreateTenant
method.
parent (:class:`str`):
@@ -166,15 +187,15 @@ async def create_tenant(
The format is "projects/{project_id}", for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (:class:`google.cloud.talent_v4beta1.types.Tenant`):
Required. The tenant to be created.
This corresponds to the ``tenant`` 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.
@@ -182,7 +203,7 @@ async def create_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4beta1.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -206,7 +227,6 @@ async def create_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if tenant is not None:
@@ -244,7 +264,7 @@ async def get_tenant(
r"""Retrieves specified tenant.
Args:
- request (:class:`~.tenant_service.GetTenantRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.GetTenantRequest`):
The request object. Request for getting a tenant by
name.
name (:class:`str`):
@@ -254,10 +274,10 @@ async def get_tenant(
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -265,7 +285,7 @@ async def get_tenant(
sent along with the request as metadata.
Returns:
- ~.tenant.Tenant:
+ google.cloud.talent_v4beta1.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -289,7 +309,6 @@ async def get_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -302,8 +321,10 @@ async def get_tenant(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -333,17 +354,17 @@ async def update_tenant(
r"""Updates specified tenant.
Args:
- request (:class:`~.tenant_service.UpdateTenantRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.UpdateTenantRequest`):
The request object. Request for updating a specified
tenant.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (:class:`google.cloud.talent_v4beta1.types.Tenant`):
Required. The tenant resource to
replace the current resource in the
system.
+
This corresponds to the ``tenant`` 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.
@@ -351,7 +372,7 @@ async def update_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4beta1.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -375,7 +396,6 @@ async def update_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if tenant is not None:
request.tenant = tenant
@@ -413,7 +433,7 @@ async def delete_tenant(
r"""Deletes specified tenant.
Args:
- request (:class:`~.tenant_service.DeleteTenantRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.DeleteTenantRequest`):
The request object. Request to delete a tenant.
name (:class:`str`):
Required. The resource name of the tenant to be deleted.
@@ -421,10 +441,10 @@ async def delete_tenant(
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -445,7 +465,6 @@ async def delete_tenant(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -458,8 +477,10 @@ async def delete_tenant(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
@@ -488,7 +509,7 @@ async def list_tenants(
r"""Lists all tenants associated with the project.
Args:
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (:class:`google.cloud.talent_v4beta1.types.ListTenantsRequest`):
The request object. List tenants for which the client
has ACL visibility.
parent (:class:`str`):
@@ -497,10 +518,10 @@ async def list_tenants(
The format is "projects/{project_id}", for example,
"projects/foo".
+
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.
@@ -508,7 +529,7 @@ async def list_tenants(
sent along with the request as metadata.
Returns:
- ~.pagers.ListTenantsAsyncPager:
+ google.cloud.talent_v4beta1.services.tenant_service.pagers.ListTenantsAsyncPager:
The List tenants response object.
Iterating over this object will yield
results and resolve additional pages
@@ -529,7 +550,6 @@ async def list_tenants(
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
@@ -542,8 +562,10 @@ async def list_tenants(
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=DEFAULT_CLIENT_INFO,
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/client.py b/google/cloud/talent_v4beta1/services/tenant_service/client.py
index 52898cda..e8971114 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/client.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/client.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from distutils import util
import os
@@ -23,10 +21,10 @@
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
-from google.api_core import exceptions # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
@@ -36,7 +34,6 @@
from google.cloud.talent_v4beta1.types import tenant
from google.cloud.talent_v4beta1.types import tenant as gct_tenant
from google.cloud.talent_v4beta1.types import tenant_service
-
from .transports.base import TenantServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import TenantServiceGrpcTransport
from .transports.grpc_asyncio import TenantServiceGrpcAsyncIOTransport
@@ -55,7 +52,7 @@ class TenantServiceClientMeta(type):
_transport_registry["grpc_asyncio"] = TenantServiceGrpcAsyncIOTransport
def get_transport_class(cls, label: str = None,) -> Type[TenantServiceTransport]:
- """Return an appropriate transport class.
+ """Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
@@ -80,7 +77,8 @@ class TenantServiceClient(metaclass=TenantServiceClientMeta):
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
- """Convert api endpoint to mTLS endpoint.
+ """Converts api endpoint to mTLS endpoint.
+
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
@@ -112,10 +110,27 @@ def _get_default_mtls_endpoint(api_endpoint):
DEFAULT_ENDPOINT
)
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ TenantServiceClient: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_info(info)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
- file.
+ file.
Args:
filename (str): The path to the service account private key json
@@ -124,7 +139,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
kwargs: Additional arguments to pass to the constructor.
Returns:
- {@api.name}: The constructed client.
+ TenantServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
@@ -134,29 +149,30 @@ def from_service_account_file(cls, filename: str, *args, **kwargs):
@property
def transport(self) -> TenantServiceTransport:
- """Return the transport used by the client instance.
+ """Returns the transport used by the client instance.
Returns:
- TenantServiceTransport: The transport used by the client instance.
+ TenantServiceTransport: The transport used by the client
+ instance.
"""
return self._transport
@staticmethod
def tenant_path(project: str, tenant: str,) -> str:
- """Return a fully-qualified tenant string."""
+ """Returns a fully-qualified tenant string."""
return "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@staticmethod
def parse_tenant_path(path: str) -> Dict[str, str]:
- """Parse a tenant path into its component segments."""
+ """Parses a tenant path into its component segments."""
m = re.match(r"^projects/(?P.+?)/tenants/(?P.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
- """Return a fully-qualified billing_account string."""
+ """Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -169,7 +185,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
@staticmethod
def common_folder_path(folder: str,) -> str:
- """Return a fully-qualified folder string."""
+ """Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
@@ -180,7 +196,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]:
@staticmethod
def common_organization_path(organization: str,) -> str:
- """Return a fully-qualified organization string."""
+ """Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
@@ -191,7 +207,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]:
@staticmethod
def common_project_path(project: str,) -> str:
- """Return a fully-qualified project string."""
+ """Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
@@ -202,7 +218,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]:
@staticmethod
def common_location_path(project: str, location: str,) -> str:
- """Return a fully-qualified location string."""
+ """Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -216,12 +232,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]:
def __init__(
self,
*,
- credentials: Optional[credentials.Credentials] = None,
+ credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, TenantServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
- """Instantiate the tenant service client.
+ """Instantiates the tenant service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
@@ -229,10 +245,10 @@ def __init__(
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
- transport (Union[str, ~.TenantServiceTransport]): The
+ transport (Union[str, TenantServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
- client_options (client_options_lib.ClientOptions): Custom options for the
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
@@ -268,21 +284,18 @@ def __init__(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
- ssl_credentials = None
+ client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
- import grpc # type: ignore
-
- cert, key = client_options.client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
is_mtls = True
+ client_cert_source_func = client_options.client_cert_source
else:
- creds = SslCredentials()
- is_mtls = creds.is_mtls
- ssl_credentials = creds.ssl_credentials if is_mtls else None
+ is_mtls = mtls.has_default_client_cert_source()
+ if is_mtls:
+ client_cert_source_func = mtls.default_client_cert_source()
+ else:
+ client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
@@ -294,12 +307,14 @@ def __init__(
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
- api_endpoint = (
- self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
- )
+ if is_mtls:
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ else:
+ api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
- "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
+ "values: never, auto, always"
)
# Save or instantiate the transport.
@@ -314,8 +329,8 @@ def __init__(
)
if client_options.scopes:
raise ValueError(
- "When providing a transport instance, "
- "provide its scopes directly."
+ "When providing a transport instance, provide its scopes "
+ "directly."
)
self._transport = transport
else:
@@ -325,7 +340,7 @@ def __init__(
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
- ssl_channel_credentials=ssl_credentials,
+ client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
)
@@ -343,24 +358,24 @@ def create_tenant(
r"""Creates a new tenant entity.
Args:
- request (:class:`~.tenant_service.CreateTenantRequest`):
+ request (google.cloud.talent_v4beta1.types.CreateTenantRequest):
The request object. The Request of the CreateTenant
method.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the project under which the
tenant is created.
The format is "projects/{project_id}", for example,
"projects/foo".
+
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (google.cloud.talent_v4beta1.types.Tenant):
Required. The tenant to be created.
This corresponds to the ``tenant`` 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.
@@ -368,7 +383,7 @@ def create_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4beta1.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -394,10 +409,8 @@ def create_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.CreateTenantRequest):
request = tenant_service.CreateTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
if tenant is not None:
@@ -431,20 +444,20 @@ def get_tenant(
r"""Retrieves specified tenant.
Args:
- request (:class:`~.tenant_service.GetTenantRequest`):
+ request (google.cloud.talent_v4beta1.types.GetTenantRequest):
The request object. Request for getting a tenant by
name.
- name (:class:`str`):
+ name (str):
Required. The resource name of the tenant to be
retrieved.
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -452,7 +465,7 @@ def get_tenant(
sent along with the request as metadata.
Returns:
- ~.tenant.Tenant:
+ google.cloud.talent_v4beta1.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -478,10 +491,8 @@ def get_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.GetTenantRequest):
request = tenant_service.GetTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -513,17 +524,17 @@ def update_tenant(
r"""Updates specified tenant.
Args:
- request (:class:`~.tenant_service.UpdateTenantRequest`):
+ request (google.cloud.talent_v4beta1.types.UpdateTenantRequest):
The request object. Request for updating a specified
tenant.
- tenant (:class:`~.gct_tenant.Tenant`):
+ tenant (google.cloud.talent_v4beta1.types.Tenant):
Required. The tenant resource to
replace the current resource in the
system.
+
This corresponds to the ``tenant`` 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.
@@ -531,7 +542,7 @@ def update_tenant(
sent along with the request as metadata.
Returns:
- ~.gct_tenant.Tenant:
+ google.cloud.talent_v4beta1.types.Tenant:
A Tenant resource represents a tenant
in the service. A tenant is a group or
entity that shares common access with
@@ -557,10 +568,8 @@ def update_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.UpdateTenantRequest):
request = tenant_service.UpdateTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if tenant is not None:
request.tenant = tenant
@@ -594,18 +603,18 @@ def delete_tenant(
r"""Deletes specified tenant.
Args:
- request (:class:`~.tenant_service.DeleteTenantRequest`):
+ request (google.cloud.talent_v4beta1.types.DeleteTenantRequest):
The request object. Request to delete a tenant.
- name (:class:`str`):
+ name (str):
Required. The resource name of the tenant to be deleted.
The format is
"projects/{project_id}/tenants/{tenant_id}", for
example, "projects/foo/tenants/bar".
+
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.
@@ -628,10 +637,8 @@ def delete_tenant(
# there are no flattened fields.
if not isinstance(request, tenant_service.DeleteTenantRequest):
request = tenant_service.DeleteTenantRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if name is not None:
request.name = name
@@ -662,19 +669,19 @@ def list_tenants(
r"""Lists all tenants associated with the project.
Args:
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListTenantsRequest):
The request object. List tenants for which the client
has ACL visibility.
- parent (:class:`str`):
+ parent (str):
Required. Resource name of the project under which the
tenant is created.
The format is "projects/{project_id}", for example,
"projects/foo".
+
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.
@@ -682,7 +689,7 @@ def list_tenants(
sent along with the request as metadata.
Returns:
- ~.pagers.ListTenantsPager:
+ google.cloud.talent_v4beta1.services.tenant_service.pagers.ListTenantsPager:
The List tenants response object.
Iterating over this object will yield
results and resolve additional pages
@@ -705,10 +712,8 @@ def list_tenants(
# there are no flattened fields.
if not isinstance(request, tenant_service.ListTenantsRequest):
request = tenant_service.ListTenantsRequest(request)
-
# If we have keyword arguments corresponding to fields on the
# request, apply these.
-
if parent is not None:
request.parent = parent
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/pagers.py b/google/cloud/talent_v4beta1/services/tenant_service/pagers.py
index 99dfee65..278ac405 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/pagers.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/pagers.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,8 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple
+from typing import (
+ Any,
+ AsyncIterable,
+ Awaitable,
+ Callable,
+ Iterable,
+ Sequence,
+ Tuple,
+ Optional,
+)
from google.cloud.talent_v4beta1.types import tenant
from google.cloud.talent_v4beta1.types import tenant_service
@@ -25,7 +32,7 @@ class ListTenantsPager:
"""A pager for iterating through ``list_tenants`` requests.
This class thinly wraps an initial
- :class:`~.tenant_service.ListTenantsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListTenantsResponse` object, and
provides an ``__iter__`` method to iterate through its
``tenants`` field.
@@ -34,7 +41,7 @@ class ListTenantsPager:
through the ``tenants`` field on the
corresponding responses.
- All the usual :class:`~.tenant_service.ListTenantsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListTenantsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -52,9 +59,9 @@ def __init__(
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListTenantsRequest):
The initial request object.
- response (:class:`~.tenant_service.ListTenantsResponse`):
+ response (google.cloud.talent_v4beta1.types.ListTenantsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
@@ -87,7 +94,7 @@ class ListTenantsAsyncPager:
"""A pager for iterating through ``list_tenants`` requests.
This class thinly wraps an initial
- :class:`~.tenant_service.ListTenantsResponse` object, and
+ :class:`google.cloud.talent_v4beta1.types.ListTenantsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``tenants`` field.
@@ -96,7 +103,7 @@ class ListTenantsAsyncPager:
through the ``tenants`` field on the
corresponding responses.
- All the usual :class:`~.tenant_service.ListTenantsResponse`
+ All the usual :class:`google.cloud.talent_v4beta1.types.ListTenantsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
@@ -109,14 +116,14 @@ def __init__(
*,
metadata: Sequence[Tuple[str, str]] = ()
):
- """Instantiate the pager.
+ """Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
- request (:class:`~.tenant_service.ListTenantsRequest`):
+ request (google.cloud.talent_v4beta1.types.ListTenantsRequest):
The initial request object.
- response (:class:`~.tenant_service.ListTenantsResponse`):
+ response (google.cloud.talent_v4beta1.types.ListTenantsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/transports/__init__.py b/google/cloud/talent_v4beta1/services/tenant_service/transports/__init__.py
index 27334b26..663ba19e 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/transports/__init__.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
from collections import OrderedDict
from typing import Dict, Type
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py b/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py
index b0f77c0d..8fc83e74 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,22 +13,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import abc
-import typing
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
+import packaging.version
import pkg_resources
-from google import auth # type: ignore
-from google.api_core import exceptions # type: ignore
+import google.auth # type: ignore
+import google.api_core # type: ignore
+from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
from google.cloud.talent_v4beta1.types import tenant
from google.cloud.talent_v4beta1.types import tenant as gct_tenant
from google.cloud.talent_v4beta1.types import tenant_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
@@ -38,6 +38,15 @@
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+try:
+ # google.auth.__version__ was added in 1.26.0
+ _GOOGLE_AUTH_VERSION = google.auth.__version__
+except AttributeError:
+ try: # try pkg_resources if it is available
+ _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
+ except pkg_resources.DistributionNotFound: # pragma: NO COVER
+ _GOOGLE_AUTH_VERSION = None
+
class TenantServiceTransport(abc.ABC):
"""Abstract transport class for TenantService."""
@@ -47,21 +56,25 @@ class TenantServiceTransport(abc.ABC):
"https://www.googleapis.com/auth/jobs",
)
+ DEFAULT_HOST: str = "jobs.googleapis.com"
+
def __init__(
self,
*,
- host: str = "jobs.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,
+ host: str = DEFAULT_HOST,
+ credentials: ga_credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -70,42 +83,77 @@ def __init__(
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.
+ scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
+ scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
+
+ # Save the scopes.
+ self._scopes = scopes
+
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
- raise exceptions.DuplicateCredentialArgs(
+ raise core_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
+ credentials, _ = google.auth.load_credentials_from_file(
+ credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
- credentials, _ = auth.default(
- scopes=scopes, quota_project_id=quota_project_id
+ credentials, _ = google.auth.default(
+ **scopes_kwargs, quota_project_id=quota_project_id
)
+ # If the credentials is service account credentials, then always try to use self signed JWT.
+ if (
+ always_use_jwt_access
+ and isinstance(credentials, service_account.Credentials)
+ and hasattr(service_account.Credentials, "with_always_use_jwt_access")
+ ):
+ credentials = credentials.with_always_use_jwt_access(True)
+
# Save the credentials.
self._credentials = credentials
- # Lifted into its own function so it can be stubbed out during tests.
- self._prep_wrapped_messages(client_info)
+ # TODO(busunkim): This method is in the base transport
+ # to avoid duplicating code across the transport classes. These functions
+ # should be deleted once the minimum required versions of google-auth is increased.
+
+ # TODO: Remove this function once google-auth >= 1.25.0 is required
+ @classmethod
+ def _get_scopes_kwargs(
+ cls, host: str, scopes: Optional[Sequence[str]]
+ ) -> Dict[str, Optional[Sequence[str]]]:
+ """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
+
+ scopes_kwargs = {}
+
+ if _GOOGLE_AUTH_VERSION and (
+ packaging.version.parse(_GOOGLE_AUTH_VERSION)
+ >= packaging.version.parse("1.25.0")
+ ):
+ scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
+ else:
+ scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
+
+ return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
@@ -120,8 +168,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -136,8 +186,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -149,8 +201,10 @@ def _prep_wrapped_messages(self, client_info):
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
- exceptions.DeadlineExceeded, exceptions.ServiceUnavailable,
+ core_exceptions.DeadlineExceeded,
+ core_exceptions.ServiceUnavailable,
),
+ deadline=30.0,
),
default_timeout=30.0,
client_info=client_info,
@@ -160,47 +214,47 @@ def _prep_wrapped_messages(self, client_info):
@property
def create_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.CreateTenantRequest],
- typing.Union[gct_tenant.Tenant, typing.Awaitable[gct_tenant.Tenant]],
+ Union[gct_tenant.Tenant, Awaitable[gct_tenant.Tenant]],
]:
raise NotImplementedError()
@property
def get_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.GetTenantRequest],
- typing.Union[tenant.Tenant, typing.Awaitable[tenant.Tenant]],
+ Union[tenant.Tenant, Awaitable[tenant.Tenant]],
]:
raise NotImplementedError()
@property
def update_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.UpdateTenantRequest],
- typing.Union[gct_tenant.Tenant, typing.Awaitable[gct_tenant.Tenant]],
+ Union[gct_tenant.Tenant, Awaitable[gct_tenant.Tenant]],
]:
raise NotImplementedError()
@property
def delete_tenant(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.DeleteTenantRequest],
- typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
]:
raise NotImplementedError()
@property
def list_tenants(
self,
- ) -> typing.Callable[
+ ) -> Callable[
[tenant_service.ListTenantsRequest],
- typing.Union[
+ Union[
tenant_service.ListTenantsResponse,
- typing.Awaitable[tenant_service.ListTenantsResponse],
+ Awaitable[tenant_service.ListTenantsResponse],
],
]:
raise NotImplementedError()
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py b/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py
index eae306f9..6315e8c4 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Callable, Dict, Optional, Sequence, Tuple
+from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+import google.auth # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
@@ -29,8 +27,7 @@
from google.cloud.talent_v4beta1.types import tenant
from google.cloud.talent_v4beta1.types import tenant as gct_tenant
from google.cloud.talent_v4beta1.types import tenant_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import TenantServiceTransport, DEFAULT_CLIENT_INFO
@@ -54,20 +51,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -91,6 +91,10 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
@@ -98,6 +102,8 @@ def __init__(
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
@@ -105,72 +111,61 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- # 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,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
-
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -178,23 +173,14 @@ def __init__(
],
)
- 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,
- client_info=client_info,
- )
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -202,7 +188,7 @@ def create_channel(
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -225,13 +211,15 @@ def create_channel(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
- scopes = scopes or cls.AUTH_SCOPES
+
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
- scopes=scopes,
quota_project_id=quota_project_id,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -320,7 +308,7 @@ def update_tenant(
@property
def delete_tenant(
self,
- ) -> Callable[[tenant_service.DeleteTenantRequest], empty.Empty]:
+ ) -> Callable[[tenant_service.DeleteTenantRequest], empty_pb2.Empty]:
r"""Return a callable for the delete tenant method over gRPC.
Deletes specified tenant.
@@ -339,7 +327,7 @@ def delete_tenant(
self._stubs["delete_tenant"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.TenantService/DeleteTenant",
request_serializer=tenant_service.DeleteTenantRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_tenant"]
diff --git a/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc_asyncio.py b/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc_asyncio.py
index cec885b2..25884b61 100644
--- a/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc_asyncio.py
+++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc_asyncio.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import warnings
-from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
-from google import auth # type: ignore
-from google.auth import credentials # type: ignore
+from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
+import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
@@ -30,8 +28,7 @@
from google.cloud.talent_v4beta1.types import tenant
from google.cloud.talent_v4beta1.types import tenant as gct_tenant
from google.cloud.talent_v4beta1.types import tenant_service
-from google.protobuf import empty_pb2 as empty # type: ignore
-
+from google.protobuf import empty_pb2 # type: ignore
from .base import TenantServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import TenantServiceGrpcTransport
@@ -57,7 +54,7 @@ class TenantServiceGrpcAsyncIOTransport(TenantServiceTransport):
def create_channel(
cls,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
@@ -65,7 +62,7 @@ def create_channel(
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
- address (Optional[str]): The host for the channel to use.
+ host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
@@ -84,13 +81,15 @@ def create_channel(
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,
+ default_scopes=cls.AUTH_SCOPES,
+ scopes=scopes,
+ default_host=cls.DEFAULT_HOST,
**kwargs,
)
@@ -98,20 +97,23 @@ def __init__(
self,
*,
host: str = "jobs.googleapis.com",
- credentials: credentials.Credentials = None,
+ credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
+ client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
- host (Optional[str]): The hostname to connect to.
+ 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
@@ -136,13 +138,19 @@ def __init__(
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
+ client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ A callback to provide client certificate bytes and private key bytes,
+ both in PEM format. It is used to configure mutual TLS channel. It is
+ ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
your own client library.
+ always_use_jwt_access (Optional[bool]): Whether self signed JWT should
+ be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
@@ -150,72 +158,60 @@ def __init__(
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
+ self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
+ self._stubs: Dict[str, Callable] = {}
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
- # Sanity check: Ensure that channel and credentials are not both
- # provided.
+ # Ignore credentials if a channel was passed.
credentials = False
-
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
- elif api_mtls_endpoint:
- warnings.warn(
- "api_mtls_endpoint and client_cert_source are deprecated",
- DeprecationWarning,
- )
-
- host = (
- api_mtls_endpoint
- if ":" in api_mtls_endpoint
- else api_mtls_endpoint + ":443"
- )
+ else:
+ if api_mtls_endpoint:
+ host = api_mtls_endpoint
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ self._ssl_channel_credentials = SslCredentials().ssl_credentials
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
-
- # Create SSL credentials with client_cert_source or application
- # default SSL credentials.
- if client_cert_source:
- cert, key = client_cert_source()
- ssl_credentials = grpc.ssl_channel_credentials(
- certificate_chain=cert, private_key=key
- )
else:
- ssl_credentials = SslCredentials().ssl_credentials
-
- # create a new channel. The provided one is ignored.
- self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
- credentials_file=credentials_file,
- ssl_credentials=ssl_credentials,
- scopes=scopes or self.AUTH_SCOPES,
- quota_project_id=quota_project_id,
- options=[
- ("grpc.max_send_message_length", -1),
- ("grpc.max_receive_message_length", -1),
- ],
- )
- self._ssl_channel_credentials = ssl_credentials
- else:
- host = host if ":" in host else host + ":443"
+ if client_cert_source_for_mtls and not ssl_channel_credentials:
+ cert, key = client_cert_source_for_mtls()
+ self._ssl_channel_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
- if credentials is None:
- credentials, _ = auth.default(
- scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
- )
+ # The base transport sets the host, credentials and scopes
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ always_use_jwt_access=always_use_jwt_access,
+ )
- # create a new channel. The provided one is ignored.
+ if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
- host,
- credentials=credentials,
+ self._host,
+ credentials=self._credentials,
credentials_file=credentials_file,
- ssl_credentials=ssl_channel_credentials,
- scopes=scopes or self.AUTH_SCOPES,
+ scopes=self._scopes,
+ ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
@@ -223,17 +219,8 @@ def __init__(
],
)
- # 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,
- client_info=client_info,
- )
-
- self._stubs = {}
+ # Wrap messages. This must be done after self._grpc_channel exists
+ self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
@@ -326,7 +313,7 @@ def update_tenant(
@property
def delete_tenant(
self,
- ) -> Callable[[tenant_service.DeleteTenantRequest], Awaitable[empty.Empty]]:
+ ) -> Callable[[tenant_service.DeleteTenantRequest], Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the delete tenant method over gRPC.
Deletes specified tenant.
@@ -345,7 +332,7 @@ def delete_tenant(
self._stubs["delete_tenant"] = self.grpc_channel.unary_unary(
"/google.cloud.talent.v4beta1.TenantService/DeleteTenant",
request_serializer=tenant_service.DeleteTenantRequest.serialize,
- response_deserializer=empty.Empty.FromString,
+ response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_tenant"]
diff --git a/google/cloud/talent_v4beta1/types/__init__.py b/google/cloud/talent_v4beta1/types/__init__.py
index 3d326265..00068206 100644
--- a/google/cloud/talent_v4beta1/types/__init__.py
+++ b/google/cloud/talent_v4beta1/types/__init__.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,53 +13,52 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
+from .application import Application
+from .application_service import (
+ CreateApplicationRequest,
+ DeleteApplicationRequest,
+ GetApplicationRequest,
+ ListApplicationsRequest,
+ ListApplicationsResponse,
+ UpdateApplicationRequest,
+)
from .common import (
- TimestampRange,
+ BatchOperationMetadata,
+ Certification,
+ CompensationInfo,
+ CustomAttribute,
+ DeviceInfo,
+ Interview,
Location,
+ Rating,
RequestMetadata,
ResponseMetadata,
- DeviceInfo,
- CustomAttribute,
- SpellingCorrection,
- CompensationInfo,
- Certification,
Skill,
- Interview,
- Rating,
- BatchOperationMetadata,
+ SpellingCorrection,
+ TimestampRange,
+ AvailabilitySignalType,
+ CommuteMethod,
CompanySize,
- JobBenefit,
+ ContactInfoUsage,
DegreeType,
EmploymentType,
- JobLevel,
+ HtmlSanitization,
+ JobBenefit,
JobCategory,
+ JobLevel,
+ Outcome,
PostingRegion,
- Visibility,
- ContactInfoUsage,
- HtmlSanitization,
- CommuteMethod,
SkillProficiencyLevel,
- Outcome,
- AvailabilitySignalType,
-)
-from .application import Application
-from .application_service import (
- CreateApplicationRequest,
- GetApplicationRequest,
- UpdateApplicationRequest,
- DeleteApplicationRequest,
- ListApplicationsRequest,
- ListApplicationsResponse,
+ Visibility,
)
from .company import Company
from .company_service import (
CreateCompanyRequest,
- GetCompanyRequest,
- UpdateCompanyRequest,
DeleteCompanyRequest,
+ GetCompanyRequest,
ListCompaniesRequest,
ListCompaniesResponse,
+ UpdateCompanyRequest,
)
from .completion_service import (
CompleteQueryRequest,
@@ -73,23 +71,23 @@
)
from .event_service import CreateClientEventRequest
from .filters import (
- JobQuery,
- ProfileQuery,
- LocationFilter,
- CompensationFilter,
- CommuteFilter,
- JobTitleFilter,
- SkillFilter,
- EmployerFilter,
- EducationFilter,
- WorkExperienceFilter,
ApplicationDateFilter,
- ApplicationOutcomeNotesFilter,
ApplicationJobFilter,
- TimeFilter,
- CandidateAvailabilityFilter,
+ ApplicationOutcomeNotesFilter,
AvailabilityFilter,
+ CandidateAvailabilityFilter,
+ CommuteFilter,
+ CompensationFilter,
+ EducationFilter,
+ EmployerFilter,
+ JobQuery,
+ JobTitleFilter,
+ LocationFilter,
PersonNameFilter,
+ ProfileQuery,
+ SkillFilter,
+ TimeFilter,
+ WorkExperienceFilter,
)
from .histogram import (
HistogramQuery,
@@ -97,168 +95,168 @@
)
from .job import Job
from .job_service import (
+ BatchCreateJobsRequest,
+ BatchDeleteJobsRequest,
+ BatchUpdateJobsRequest,
CreateJobRequest,
- GetJobRequest,
- UpdateJobRequest,
DeleteJobRequest,
- BatchDeleteJobsRequest,
+ GetJobRequest,
+ JobOperationResult,
ListJobsRequest,
ListJobsResponse,
SearchJobsRequest,
SearchJobsResponse,
- BatchCreateJobsRequest,
- BatchUpdateJobsRequest,
- JobOperationResult,
+ UpdateJobRequest,
JobView,
)
from .profile import (
- Profile,
- AvailabilitySignal,
- Resume,
- PersonName,
+ Activity,
+ AdditionalContactInfo,
Address,
+ AvailabilitySignal,
+ Degree,
+ EducationRecord,
Email,
- Phone,
- PersonalUri,
- AdditionalContactInfo,
EmploymentRecord,
- EducationRecord,
- Degree,
- Activity,
- Publication,
Patent,
+ PersonalUri,
+ PersonName,
+ Phone,
+ Profile,
+ Publication,
+ Resume,
)
from .profile_service import (
- ListProfilesRequest,
- ListProfilesResponse,
CreateProfileRequest,
- GetProfileRequest,
- UpdateProfileRequest,
DeleteProfileRequest,
+ GetProfileRequest,
+ ListProfilesRequest,
+ ListProfilesResponse,
SearchProfilesRequest,
SearchProfilesResponse,
SummarizedProfile,
+ UpdateProfileRequest,
)
from .tenant import Tenant
from .tenant_service import (
CreateTenantRequest,
- GetTenantRequest,
- UpdateTenantRequest,
DeleteTenantRequest,
+ GetTenantRequest,
ListTenantsRequest,
ListTenantsResponse,
+ UpdateTenantRequest,
)
__all__ = (
- "TimestampRange",
+ "Application",
+ "CreateApplicationRequest",
+ "DeleteApplicationRequest",
+ "GetApplicationRequest",
+ "ListApplicationsRequest",
+ "ListApplicationsResponse",
+ "UpdateApplicationRequest",
+ "BatchOperationMetadata",
+ "Certification",
+ "CompensationInfo",
+ "CustomAttribute",
+ "DeviceInfo",
+ "Interview",
"Location",
+ "Rating",
"RequestMetadata",
"ResponseMetadata",
- "DeviceInfo",
- "CustomAttribute",
- "SpellingCorrection",
- "CompensationInfo",
- "Certification",
"Skill",
- "Interview",
- "Rating",
- "BatchOperationMetadata",
+ "SpellingCorrection",
+ "TimestampRange",
+ "AvailabilitySignalType",
+ "CommuteMethod",
"CompanySize",
- "JobBenefit",
+ "ContactInfoUsage",
"DegreeType",
"EmploymentType",
- "JobLevel",
+ "HtmlSanitization",
+ "JobBenefit",
"JobCategory",
+ "JobLevel",
+ "Outcome",
"PostingRegion",
- "Visibility",
- "ContactInfoUsage",
- "HtmlSanitization",
- "CommuteMethod",
"SkillProficiencyLevel",
- "Outcome",
- "AvailabilitySignalType",
- "Application",
- "CreateApplicationRequest",
- "GetApplicationRequest",
- "UpdateApplicationRequest",
- "DeleteApplicationRequest",
- "ListApplicationsRequest",
- "ListApplicationsResponse",
+ "Visibility",
"Company",
"CreateCompanyRequest",
- "GetCompanyRequest",
- "UpdateCompanyRequest",
"DeleteCompanyRequest",
+ "GetCompanyRequest",
"ListCompaniesRequest",
"ListCompaniesResponse",
+ "UpdateCompanyRequest",
"CompleteQueryRequest",
"CompleteQueryResponse",
"ClientEvent",
"JobEvent",
"ProfileEvent",
"CreateClientEventRequest",
- "JobQuery",
- "ProfileQuery",
- "LocationFilter",
- "CompensationFilter",
- "CommuteFilter",
- "JobTitleFilter",
- "SkillFilter",
- "EmployerFilter",
- "EducationFilter",
- "WorkExperienceFilter",
"ApplicationDateFilter",
- "ApplicationOutcomeNotesFilter",
"ApplicationJobFilter",
- "TimeFilter",
- "CandidateAvailabilityFilter",
+ "ApplicationOutcomeNotesFilter",
"AvailabilityFilter",
+ "CandidateAvailabilityFilter",
+ "CommuteFilter",
+ "CompensationFilter",
+ "EducationFilter",
+ "EmployerFilter",
+ "JobQuery",
+ "JobTitleFilter",
+ "LocationFilter",
"PersonNameFilter",
+ "ProfileQuery",
+ "SkillFilter",
+ "TimeFilter",
+ "WorkExperienceFilter",
"HistogramQuery",
"HistogramQueryResult",
"Job",
+ "BatchCreateJobsRequest",
+ "BatchDeleteJobsRequest",
+ "BatchUpdateJobsRequest",
"CreateJobRequest",
- "GetJobRequest",
- "UpdateJobRequest",
"DeleteJobRequest",
- "BatchDeleteJobsRequest",
+ "GetJobRequest",
+ "JobOperationResult",
"ListJobsRequest",
"ListJobsResponse",
"SearchJobsRequest",
"SearchJobsResponse",
- "BatchCreateJobsRequest",
- "BatchUpdateJobsRequest",
- "JobOperationResult",
+ "UpdateJobRequest",
"JobView",
- "Profile",
- "AvailabilitySignal",
- "Resume",
- "PersonName",
+ "Activity",
+ "AdditionalContactInfo",
"Address",
+ "AvailabilitySignal",
+ "Degree",
+ "EducationRecord",
"Email",
- "Phone",
- "PersonalUri",
- "AdditionalContactInfo",
"EmploymentRecord",
- "EducationRecord",
- "Degree",
- "Activity",
- "Publication",
"Patent",
- "ListProfilesRequest",
- "ListProfilesResponse",
+ "PersonalUri",
+ "PersonName",
+ "Phone",
+ "Profile",
+ "Publication",
+ "Resume",
"CreateProfileRequest",
- "GetProfileRequest",
- "UpdateProfileRequest",
"DeleteProfileRequest",
+ "GetProfileRequest",
+ "ListProfilesRequest",
+ "ListProfilesResponse",
"SearchProfilesRequest",
"SearchProfilesResponse",
"SummarizedProfile",
+ "UpdateProfileRequest",
"Tenant",
"CreateTenantRequest",
- "GetTenantRequest",
- "UpdateTenantRequest",
"DeleteTenantRequest",
+ "GetTenantRequest",
"ListTenantsRequest",
"ListTenantsResponse",
+ "UpdateTenantRequest",
)
diff --git a/google/cloud/talent_v4beta1/types/application.py b/google/cloud/talent_v4beta1/types/application.py
index c407b4bc..13948ea3 100644
--- a/google/cloud/talent_v4beta1/types/application.py
+++ b/google/cloud/talent_v4beta1/types/application.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,14 +13,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -69,9 +66,9 @@ class Application(proto.Message):
The format is
"projects/{project_id}/tenants/{tenant_id}/companies/{company_id}".
For example, "projects/foo/tenants/bar/companies/baz".
- application_date (~.date.Date):
+ application_date (google.type.date_pb2.Date):
The application date.
- stage (~.application.Application.ApplicationStage):
+ stage (google.cloud.talent_v4beta1.types.Application.ApplicationStage):
Required. What is the most recent stage of
the application (that is, new, screen, send cv,
hired, finished work)? This field is
@@ -79,19 +76,19 @@ class Application(proto.Message):
possible status, but instead, represents
statuses that would be used to indicate to the
ML models good / bad matches.
- state (~.application.Application.ApplicationState):
+ state (google.cloud.talent_v4beta1.types.Application.ApplicationState):
The application state.
- interviews (Sequence[~.common.Interview]):
+ interviews (Sequence[google.cloud.talent_v4beta1.types.Interview]):
All interviews (screen, onsite, and so on)
conducted as part of this application (includes
details such as user conducting the interview,
timestamp, feedback, and so on).
- referral (~.wrappers.BoolValue):
+ referral (google.protobuf.wrappers_pb2.BoolValue):
If the candidate is referred by a employee.
- create_time (~.timestamp.Timestamp):
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
Required. Reflects the time that the
application was created.
- update_time (~.timestamp.Timestamp):
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
The last update timestamp.
outcome_notes (str):
Free text reason behind the recruitement
@@ -99,10 +96,10 @@ class Application(proto.Message):
reject, reason for an unsuccessful finish, and
so on).
Number of characters allowed is 100.
- outcome (~.common.Outcome):
+ outcome (google.cloud.talent_v4beta1.types.Outcome):
Outcome positiveness shows how positive the
outcome is.
- is_match (~.wrappers.BoolValue):
+ is_match (google.protobuf.wrappers_pb2.BoolValue):
Output only. Indicates whether this job
application is a match to application related
filters. This value is only applicable in
@@ -134,39 +131,28 @@ class ApplicationStage(proto.Enum):
OFFER_ACCEPTED = 6
STARTED = 7
- name = proto.Field(proto.STRING, number=1)
-
- external_id = proto.Field(proto.STRING, number=31)
-
- profile = proto.Field(proto.STRING, number=2)
-
- job = proto.Field(proto.STRING, number=4)
-
- company = proto.Field(proto.STRING, number=5)
-
- application_date = proto.Field(proto.MESSAGE, number=7, message=date.Date,)
-
+ name = proto.Field(proto.STRING, number=1,)
+ external_id = proto.Field(proto.STRING, number=31,)
+ profile = proto.Field(proto.STRING, number=2,)
+ job = proto.Field(proto.STRING, number=4,)
+ company = proto.Field(proto.STRING, number=5,)
+ application_date = proto.Field(proto.MESSAGE, number=7, message=date_pb2.Date,)
stage = proto.Field(proto.ENUM, number=11, enum=ApplicationStage,)
-
state = proto.Field(proto.ENUM, number=13, enum=ApplicationState,)
-
interviews = proto.RepeatedField(
proto.MESSAGE, number=16, message=common.Interview,
)
-
- referral = proto.Field(proto.MESSAGE, number=18, message=wrappers.BoolValue,)
-
- create_time = proto.Field(proto.MESSAGE, number=19, message=timestamp.Timestamp,)
-
- update_time = proto.Field(proto.MESSAGE, number=20, message=timestamp.Timestamp,)
-
- outcome_notes = proto.Field(proto.STRING, number=21)
-
+ referral = proto.Field(proto.MESSAGE, number=18, message=wrappers_pb2.BoolValue,)
+ create_time = proto.Field(
+ proto.MESSAGE, number=19, message=timestamp_pb2.Timestamp,
+ )
+ update_time = proto.Field(
+ proto.MESSAGE, number=20, message=timestamp_pb2.Timestamp,
+ )
+ outcome_notes = proto.Field(proto.STRING, number=21,)
outcome = proto.Field(proto.ENUM, number=22, enum=common.Outcome,)
-
- is_match = proto.Field(proto.MESSAGE, number=28, message=wrappers.BoolValue,)
-
- job_title_snippet = proto.Field(proto.STRING, number=29)
+ is_match = proto.Field(proto.MESSAGE, number=28, message=wrappers_pb2.BoolValue,)
+ job_title_snippet = proto.Field(proto.STRING, number=29,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4beta1/types/application_service.py b/google/cloud/talent_v4beta1/types/application_service.py
index 8c906e91..1a9afbce 100644
--- a/google/cloud/talent_v4beta1/types/application_service.py
+++ b/google/cloud/talent_v4beta1/types/application_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,13 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import application as gct_application
from google.cloud.talent_v4beta1.types import common
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -38,7 +35,6 @@
class CreateApplicationRequest(proto.Message):
r"""The Request of the CreateApplication method.
-
Attributes:
parent (str):
Required. Resource name of the profile under which the
@@ -47,12 +43,11 @@ class CreateApplicationRequest(proto.Message):
The format is
"projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}".
For example, "projects/foo/tenants/bar/profiles/baz".
- application (~.gct_application.Application):
+ application (google.cloud.talent_v4beta1.types.Application):
Required. The application to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
application = proto.Field(
proto.MESSAGE, number=2, message=gct_application.Application,
)
@@ -60,7 +55,6 @@ class CreateApplicationRequest(proto.Message):
class GetApplicationRequest(proto.Message):
r"""Request for getting a application by name.
-
Attributes:
name (str):
Required. The resource name of the application to be
@@ -72,17 +66,16 @@ class GetApplicationRequest(proto.Message):
"projects/foo/tenants/bar/profiles/baz/applications/qux".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateApplicationRequest(proto.Message):
r"""Request for updating a specified application.
-
Attributes:
- application (~.gct_application.Application):
+ application (google.cloud.talent_v4beta1.types.Application):
Required. The application resource to replace
the current resource in the system.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -100,13 +93,13 @@ class UpdateApplicationRequest(proto.Message):
application = proto.Field(
proto.MESSAGE, number=1, message=gct_application.Application,
)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteApplicationRequest(proto.Message):
r"""Request to delete a application.
-
Attributes:
name (str):
Required. The resource name of the application to be
@@ -118,12 +111,11 @@ class DeleteApplicationRequest(proto.Message):
"projects/foo/tenants/bar/profiles/baz/applications/qux".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class ListApplicationsRequest(proto.Message):
r"""List applications for which the client has ACL visibility.
-
Attributes:
parent (str):
Required. Resource name of the profile under which the
@@ -141,22 +133,19 @@ class ListApplicationsRequest(proto.Message):
positive number is provided.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- page_token = proto.Field(proto.STRING, number=2)
-
- page_size = proto.Field(proto.INT32, number=3)
+ parent = proto.Field(proto.STRING, number=1,)
+ page_token = proto.Field(proto.STRING, number=2,)
+ page_size = proto.Field(proto.INT32, number=3,)
class ListApplicationsResponse(proto.Message):
r"""The List applications response object.
-
Attributes:
- applications (Sequence[~.gct_application.Application]):
+ applications (Sequence[google.cloud.talent_v4beta1.types.Application]):
Applications for the current client.
next_page_token (str):
A token to retrieve the next page of results.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4beta1.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
@@ -168,9 +157,7 @@ def raw_page(self):
applications = proto.RepeatedField(
proto.MESSAGE, number=1, message=gct_application.Application,
)
-
- next_page_token = proto.Field(proto.STRING, number=2)
-
+ next_page_token = proto.Field(proto.STRING, number=2,)
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
diff --git a/google/cloud/talent_v4beta1/types/batch.py b/google/cloud/talent_v4beta1/types/batch.py
index fdbff5f8..a17076fc 100644
--- a/google/cloud/talent_v4beta1/types/batch.py
+++ b/google/cloud/talent_v4beta1/types/batch.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
diff --git a/google/cloud/talent_v4beta1/types/common.py b/google/cloud/talent_v4beta1/types/common.py
index 61614a0a..b8b2cc77 100644
--- a/google/cloud/talent_v4beta1/types/common.py
+++ b/google/cloud/talent_v4beta1/types/common.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,16 +13,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import money_pb2 as money # type: ignore
-from google.type import postal_address_pb2 as gt_postal_address # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import money_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -187,6 +184,7 @@ class Visibility(proto.Enum):
r"""Deprecated. All resources are only visible to the owner.
An enum that represents who has view access to the resource.
"""
+ _pb_options = {"deprecated": True}
VISIBILITY_UNSPECIFIED = 0
ACCOUNT_ONLY = 1
SHARED_WITH_GOOGLE = 2
@@ -252,17 +250,15 @@ class AvailabilitySignalType(proto.Enum):
class TimestampRange(proto.Message):
r"""Message representing a period of time between two timestamps.
-
Attributes:
- start_time (~.timestamp.Timestamp):
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
Begin of the period (inclusive).
- end_time (~.timestamp.Timestamp):
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
End of the period (exclusive).
"""
- start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,)
-
- end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
+ start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
+ end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
class Location(proto.Message):
@@ -270,7 +266,7 @@ class Location(proto.Message):
information.
Attributes:
- location_type (~.common.Location.LocationType):
+ location_type (google.cloud.talent_v4beta1.types.Location.LocationType):
The type of a location, which corresponds to the address
lines field of
[google.type.PostalAddress][google.type.PostalAddress]. For
@@ -278,13 +274,13 @@ class Location(proto.Message):
[LocationType.NEIGHBORHOOD][google.cloud.talent.v4beta1.Location.LocationType.NEIGHBORHOOD],
and "Kansas City, KS, USA" has a type of
[LocationType.LOCALITY][google.cloud.talent.v4beta1.Location.LocationType.LOCALITY].
- postal_address (~.gt_postal_address.PostalAddress):
+ postal_address (google.type.postal_address_pb2.PostalAddress):
Postal address of the location that includes
human readable information, such as postal
delivery and payments addresses. Given a postal
address, a postal service can deliver items to a
premises, P.O. Box, or other delivery location.
- lat_lng (~.latlng.LatLng):
+ lat_lng (google.type.latlng_pb2.LatLng):
An object representing a latitude/longitude
pair.
radius_miles (float):
@@ -311,14 +307,11 @@ class LocationType(proto.Enum):
STREET_ADDRESS = 10
location_type = proto.Field(proto.ENUM, number=1, enum=LocationType,)
-
postal_address = proto.Field(
- proto.MESSAGE, number=2, message=gt_postal_address.PostalAddress,
+ proto.MESSAGE, number=2, message=postal_address_pb2.PostalAddress,
)
-
- lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng.LatLng,)
-
- radius_miles = proto.Field(proto.DOUBLE, number=4)
+ lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng_pb2.LatLng,)
+ radius_miles = proto.Field(proto.DOUBLE, number=4,)
class RequestMetadata(proto.Message):
@@ -390,19 +383,15 @@ class RequestMetadata(proto.Message):
and
[user_id][google.cloud.talent.v4beta1.RequestMetadata.user_id]
for the best service experience.
- device_info (~.common.DeviceInfo):
+ device_info (google.cloud.talent_v4beta1.types.DeviceInfo):
The type of device used by the job seeker at
the time of the call to the service.
"""
- domain = proto.Field(proto.STRING, number=1)
-
- session_id = proto.Field(proto.STRING, number=2)
-
- user_id = proto.Field(proto.STRING, number=3)
-
- allow_missing_ids = proto.Field(proto.BOOL, number=4)
-
+ domain = proto.Field(proto.STRING, number=1,)
+ session_id = proto.Field(proto.STRING, number=2,)
+ user_id = proto.Field(proto.STRING, number=3,)
+ allow_missing_ids = proto.Field(proto.BOOL, number=4,)
device_info = proto.Field(proto.MESSAGE, number=5, message="DeviceInfo",)
@@ -416,7 +405,7 @@ class ResponseMetadata(proto.Message):
This id is logged for tracking purposes.
"""
- request_id = proto.Field(proto.STRING, number=1)
+ request_id = proto.Field(proto.STRING, number=1,)
class DeviceInfo(proto.Message):
@@ -426,7 +415,7 @@ class DeviceInfo(proto.Message):
devices.
Attributes:
- device_type (~.common.DeviceInfo.DeviceType):
+ device_type (google.cloud.talent_v4beta1.types.DeviceInfo.DeviceType):
Type of the device.
id (str):
A device-specific ID. The ID must be a unique
@@ -447,8 +436,7 @@ class DeviceType(proto.Enum):
OTHER = 6
device_type = proto.Field(proto.ENUM, number=1, enum=DeviceType,)
-
- id = proto.Field(proto.STRING, number=2)
+ id = proto.Field(proto.STRING, number=2,)
class CustomAttribute(proto.Message):
@@ -493,16 +481,13 @@ class CustomAttribute(proto.Message):
Default is false.
"""
- string_values = proto.RepeatedField(proto.STRING, number=1)
-
- long_values = proto.RepeatedField(proto.INT64, number=2)
-
- filterable = proto.Field(proto.BOOL, number=3)
+ string_values = proto.RepeatedField(proto.STRING, number=1,)
+ long_values = proto.RepeatedField(proto.INT64, number=2,)
+ filterable = proto.Field(proto.BOOL, number=3,)
class SpellingCorrection(proto.Message):
r"""Spell check result.
-
Attributes:
corrected (bool):
Indicates if the query was corrected by the
@@ -521,25 +506,22 @@ class SpellingCorrection(proto.Message):
"software engineer".
"""
- corrected = proto.Field(proto.BOOL, number=1)
-
- corrected_text = proto.Field(proto.STRING, number=2)
-
- corrected_html = proto.Field(proto.STRING, number=3)
+ corrected = proto.Field(proto.BOOL, number=1,)
+ corrected_text = proto.Field(proto.STRING, number=2,)
+ corrected_html = proto.Field(proto.STRING, number=3,)
class CompensationInfo(proto.Message):
r"""Job compensation details.
-
Attributes:
- entries (Sequence[~.common.CompensationInfo.CompensationEntry]):
+ entries (Sequence[google.cloud.talent_v4beta1.types.CompensationInfo.CompensationEntry]):
Job compensation information.
At most one entry can be of type
[CompensationInfo.CompensationType.BASE][google.cloud.talent.v4beta1.CompensationInfo.CompensationType.BASE],
which is referred as **base compensation entry** for the
job.
- annualized_base_compensation_range (~.common.CompensationInfo.CompensationRange):
+ annualized_base_compensation_range (google.cloud.talent_v4beta1.types.CompensationInfo.CompensationRange):
Output only. Annualized base compensation range. Computed as
base compensation entry's
[CompensationEntry.amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount]
@@ -549,7 +531,7 @@ class CompensationInfo(proto.Message):
See
[CompensationEntry][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry]
for explanation on compensation annualization.
- annualized_total_compensation_range (~.common.CompensationInfo.CompensationRange):
+ annualized_total_compensation_range (google.cloud.talent_v4beta1.types.CompensationInfo.CompensationRange):
Output only. Annualized total compensation range. Computed
as all compensation entries'
[CompensationEntry.amount][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.amount]
@@ -631,25 +613,25 @@ class CompensationEntry(proto.Message):
[expected_units_per_year][google.cloud.talent.v4beta1.CompensationInfo.CompensationEntry.expected_units_per_year].
Attributes:
- type_ (~.common.CompensationInfo.CompensationType):
+ type_ (google.cloud.talent_v4beta1.types.CompensationInfo.CompensationType):
Compensation type.
Default is
[CompensationType.COMPENSATION_TYPE_UNSPECIFIED][google.cloud.talent.v4beta1.CompensationInfo.CompensationType.COMPENSATION_TYPE_UNSPECIFIED].
- unit (~.common.CompensationInfo.CompensationUnit):
+ unit (google.cloud.talent_v4beta1.types.CompensationInfo.CompensationUnit):
Frequency of the specified amount.
Default is
[CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED].
- amount (~.money.Money):
+ amount (google.type.money_pb2.Money):
Compensation amount.
- range_ (~.common.CompensationInfo.CompensationRange):
+ range_ (google.cloud.talent_v4beta1.types.CompensationInfo.CompensationRange):
Compensation range.
description (str):
Compensation description. For example, could
indicate equity terms or provide additional
context to an estimated bonus.
- expected_units_per_year (~.wrappers.DoubleValue):
+ expected_units_per_year (google.protobuf.wrappers_pb2.DoubleValue):
Expected number of units paid each year. If not specified,
when
[Job.employment_types][google.cloud.talent.v4beta1.Job.employment_types]
@@ -667,54 +649,52 @@ class CompensationEntry(proto.Message):
type_ = proto.Field(
proto.ENUM, number=1, enum="CompensationInfo.CompensationType",
)
-
unit = proto.Field(
proto.ENUM, number=2, enum="CompensationInfo.CompensationUnit",
)
-
amount = proto.Field(
- proto.MESSAGE, number=3, oneof="compensation_amount", message=money.Money,
+ proto.MESSAGE,
+ number=3,
+ oneof="compensation_amount",
+ message=money_pb2.Money,
)
-
range_ = proto.Field(
proto.MESSAGE,
number=4,
oneof="compensation_amount",
message="CompensationInfo.CompensationRange",
)
-
- description = proto.Field(proto.STRING, number=5)
-
+ description = proto.Field(proto.STRING, number=5,)
expected_units_per_year = proto.Field(
- proto.MESSAGE, number=6, message=wrappers.DoubleValue,
+ proto.MESSAGE, number=6, message=wrappers_pb2.DoubleValue,
)
class CompensationRange(proto.Message):
r"""Compensation range.
-
Attributes:
- max_compensation (~.money.Money):
+ max_compensation (google.type.money_pb2.Money):
The maximum amount of compensation. If left empty, the value
is set to a maximal compensation value and the currency code
is set to match the [currency
code][google.type.Money.currency_code] of min_compensation.
- min_compensation (~.money.Money):
+ min_compensation (google.type.money_pb2.Money):
The minimum amount of compensation. If left empty, the value
is set to zero and the currency code is set to match the
[currency code][google.type.Money.currency_code] of
max_compensation.
"""
- max_compensation = proto.Field(proto.MESSAGE, number=2, message=money.Money,)
-
- min_compensation = proto.Field(proto.MESSAGE, number=1, message=money.Money,)
+ max_compensation = proto.Field(
+ proto.MESSAGE, number=2, message=money_pb2.Money,
+ )
+ min_compensation = proto.Field(
+ proto.MESSAGE, number=1, message=money_pb2.Money,
+ )
entries = proto.RepeatedField(proto.MESSAGE, number=1, message=CompensationEntry,)
-
annualized_base_compensation_range = proto.Field(
proto.MESSAGE, number=2, message=CompensationRange,
)
-
annualized_total_compensation_range = proto.Field(
proto.MESSAGE, number=3, message=CompensationRange,
)
@@ -722,15 +702,14 @@ class CompensationRange(proto.Message):
class Certification(proto.Message):
r"""Resource that represents a license or certification.
-
Attributes:
display_name (str):
Name of license or certification.
Number of characters allowed is 100.
- acquire_date (~.date.Date):
+ acquire_date (google.type.date_pb2.Date):
Acquisition date or effective date of license
or certification.
- expire_date (~.date.Date):
+ expire_date (google.type.date_pb2.Date):
Expiration date of license of certification.
authority (str):
Authority of license, such as government.
@@ -740,29 +719,24 @@ class Certification(proto.Message):
Number of characters allowed is 100,000.
"""
- display_name = proto.Field(proto.STRING, number=1)
-
- acquire_date = proto.Field(proto.MESSAGE, number=2, message=date.Date,)
-
- expire_date = proto.Field(proto.MESSAGE, number=3, message=date.Date,)
-
- authority = proto.Field(proto.STRING, number=4)
-
- description = proto.Field(proto.STRING, number=5)
+ display_name = proto.Field(proto.STRING, number=1,)
+ acquire_date = proto.Field(proto.MESSAGE, number=2, message=date_pb2.Date,)
+ expire_date = proto.Field(proto.MESSAGE, number=3, message=date_pb2.Date,)
+ authority = proto.Field(proto.STRING, number=4,)
+ description = proto.Field(proto.STRING, number=5,)
class Skill(proto.Message):
r"""Resource that represents a skill of a candidate.
-
Attributes:
display_name (str):
Skill display name.
For example, "Java", "Python".
Number of characters allowed is 100.
- last_used_date (~.date.Date):
+ last_used_date (google.type.date_pb2.Date):
The last time this skill was used.
- level (~.common.SkillProficiencyLevel):
+ level (google.cloud.talent_v4beta1.types.SkillProficiencyLevel):
Skill proficiency level which indicates how
proficient the candidate is at this skill.
context (str):
@@ -776,30 +750,24 @@ class Skill(proto.Message):
isn't related to the search query.
"""
- display_name = proto.Field(proto.STRING, number=1)
-
- last_used_date = proto.Field(proto.MESSAGE, number=2, message=date.Date,)
-
+ display_name = proto.Field(proto.STRING, number=1,)
+ last_used_date = proto.Field(proto.MESSAGE, number=2, message=date_pb2.Date,)
level = proto.Field(proto.ENUM, number=3, enum="SkillProficiencyLevel",)
-
- context = proto.Field(proto.STRING, number=4)
-
- skill_name_snippet = proto.Field(proto.STRING, number=5)
+ context = proto.Field(proto.STRING, number=4,)
+ skill_name_snippet = proto.Field(proto.STRING, number=5,)
class Interview(proto.Message):
r"""Details of an interview.
-
Attributes:
- rating (~.common.Rating):
+ rating (google.cloud.talent_v4beta1.types.Rating):
The rating on this interview.
- outcome (~.common.Outcome):
+ outcome (google.cloud.talent_v4beta1.types.Outcome):
Required. The overall decision resulting from
this interview (positive, negative, nuetral).
"""
rating = proto.Field(proto.MESSAGE, number=6, message="Rating",)
-
outcome = proto.Field(proto.ENUM, number=7, enum="Outcome",)
@@ -820,13 +788,10 @@ class Rating(proto.Message):
score can be 1, 2, 3, 4, or 5)
"""
- overall = proto.Field(proto.DOUBLE, number=1)
-
- min_ = proto.Field(proto.DOUBLE, number=2)
-
- max_ = proto.Field(proto.DOUBLE, number=3)
-
- interval = proto.Field(proto.DOUBLE, number=4)
+ overall = proto.Field(proto.DOUBLE, number=1,)
+ min_ = proto.Field(proto.DOUBLE, number=2,)
+ max_ = proto.Field(proto.DOUBLE, number=3,)
+ interval = proto.Field(proto.DOUBLE, number=4,)
class BatchOperationMetadata(proto.Message):
@@ -835,7 +800,7 @@ class BatchOperationMetadata(proto.Message):
[google.longrunning.Operation.metadata][google.longrunning.Operation.metadata].
Attributes:
- state (~.common.BatchOperationMetadata.State):
+ state (google.cloud.talent_v4beta1.types.BatchOperationMetadata.State):
The state of a long running operation.
state_description (str):
More detailed information about operation
@@ -847,14 +812,14 @@ class BatchOperationMetadata(proto.Message):
Count of failed item(s) inside an operation.
total_count (int):
Count of total item(s) inside an operation.
- create_time (~.timestamp.Timestamp):
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
The time when the batch operation is created.
- update_time (~.timestamp.Timestamp):
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
The time when the batch operation status is updated. The
metadata and the
[update_time][google.cloud.talent.v4beta1.BatchOperationMetadata.update_time]
is refreshed every minute otherwise cached data is returned.
- end_time (~.timestamp.Timestamp):
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
The time when the batch operation is finished and
[google.longrunning.Operation.done][google.longrunning.Operation.done]
is set to ``true``.
@@ -871,20 +836,13 @@ class State(proto.Enum):
CANCELLED = 6
state = proto.Field(proto.ENUM, number=1, enum=State,)
-
- state_description = proto.Field(proto.STRING, number=2)
-
- success_count = proto.Field(proto.INT32, number=3)
-
- failure_count = proto.Field(proto.INT32, number=4)
-
- total_count = proto.Field(proto.INT32, number=5)
-
- create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,)
-
- update_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,)
-
- end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,)
+ state_description = proto.Field(proto.STRING, number=2,)
+ success_count = proto.Field(proto.INT32, number=3,)
+ failure_count = proto.Field(proto.INT32, number=4,)
+ total_count = proto.Field(proto.INT32, number=5,)
+ create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,)
+ update_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,)
+ end_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4beta1/types/company.py b/google/cloud/talent_v4beta1/types/company.py
index ac333e29..0279ec95 100644
--- a/google/cloud/talent_v4beta1/types/company.py
+++ b/google/cloud/talent_v4beta1/types/company.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,10 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
@@ -53,7 +50,7 @@ class Company(proto.Message):
used to uniquely identify the company.
The maximum number of allowed characters is 255.
- size (~.common.CompanySize):
+ size (google.cloud.talent_v4beta1.types.CompanySize):
The employer's company size.
headquarters_address (str):
The street address of the company's main headquarters, which
@@ -92,7 +89,7 @@ class Company(proto.Message):
search keyword. Custom field values with parenthesis,
brackets and special symbols are not searchable as-is, and
those keyword queries must be surrounded by quotes.
- derived_info (~.company.Company.DerivedInfo):
+ derived_info (google.cloud.talent_v4beta1.types.Company.DerivedInfo):
Output only. Derived details about the
company.
suspended (bool):
@@ -104,9 +101,8 @@ class Company(proto.Message):
class DerivedInfo(proto.Message):
r"""Derived details about the company.
-
Attributes:
- headquarters_location (~.common.Location):
+ headquarters_location (google.cloud.talent_v4beta1.types.Location):
A structured headquarters location of the company, resolved
from
[Company.headquarters_address][google.cloud.talent.v4beta1.Company.headquarters_address]
@@ -117,33 +113,21 @@ class DerivedInfo(proto.Message):
proto.MESSAGE, number=1, message=common.Location,
)
- name = proto.Field(proto.STRING, number=1)
-
- display_name = proto.Field(proto.STRING, number=2)
-
- external_id = proto.Field(proto.STRING, number=3)
-
+ name = proto.Field(proto.STRING, number=1,)
+ display_name = proto.Field(proto.STRING, number=2,)
+ external_id = proto.Field(proto.STRING, number=3,)
size = proto.Field(proto.ENUM, number=4, enum=common.CompanySize,)
-
- headquarters_address = proto.Field(proto.STRING, number=5)
-
- hiring_agency = proto.Field(proto.BOOL, number=6)
-
- eeo_text = proto.Field(proto.STRING, number=7)
-
- website_uri = proto.Field(proto.STRING, number=8)
-
- career_site_uri = proto.Field(proto.STRING, number=9)
-
- image_uri = proto.Field(proto.STRING, number=10)
-
+ headquarters_address = proto.Field(proto.STRING, number=5,)
+ hiring_agency = proto.Field(proto.BOOL, number=6,)
+ eeo_text = proto.Field(proto.STRING, number=7,)
+ website_uri = proto.Field(proto.STRING, number=8,)
+ career_site_uri = proto.Field(proto.STRING, number=9,)
+ image_uri = proto.Field(proto.STRING, number=10,)
keyword_searchable_job_custom_attributes = proto.RepeatedField(
- proto.STRING, number=11
+ proto.STRING, number=11,
)
-
derived_info = proto.Field(proto.MESSAGE, number=12, message=DerivedInfo,)
-
- suspended = proto.Field(proto.BOOL, number=13)
+ suspended = proto.Field(proto.BOOL, number=13,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4beta1/types/company_service.py b/google/cloud/talent_v4beta1/types/company_service.py
index 960ab39c..9b33f700 100644
--- a/google/cloud/talent_v4beta1/types/company_service.py
+++ b/google/cloud/talent_v4beta1/types/company_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,13 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import company as gct_company
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -38,7 +35,6 @@
class CreateCompanyRequest(proto.Message):
r"""The Request of the CreateCompany method.
-
Attributes:
parent (str):
Required. Resource name of the tenant under which the
@@ -48,18 +44,16 @@ class CreateCompanyRequest(proto.Message):
for example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created, for example,
"projects/foo".
- company (~.gct_company.Company):
+ company (google.cloud.talent_v4beta1.types.Company):
Required. The company to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
company = proto.Field(proto.MESSAGE, number=2, message=gct_company.Company,)
class GetCompanyRequest(proto.Message):
r"""Request for getting a company by name.
-
Attributes:
name (str):
Required. The resource name of the company to be retrieved.
@@ -73,17 +67,16 @@ class GetCompanyRequest(proto.Message):
example, "projects/api-test-project/companies/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateCompanyRequest(proto.Message):
r"""Request for updating a specified company.
-
Attributes:
- company (~.gct_company.Company):
+ company (google.cloud.talent_v4beta1.types.Company):
Required. The company resource to replace the
current resource in the system.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -99,13 +92,13 @@ class UpdateCompanyRequest(proto.Message):
"""
company = proto.Field(proto.MESSAGE, number=1, message=gct_company.Company,)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteCompanyRequest(proto.Message):
r"""Request to delete a company.
-
Attributes:
name (str):
Required. The resource name of the company to be deleted.
@@ -118,12 +111,11 @@ class DeleteCompanyRequest(proto.Message):
example, "projects/foo/companies/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class ListCompaniesRequest(proto.Message):
r"""List companies for which the client has ACL visibility.
-
Attributes:
parent (str):
Required. Resource name of the tenant under which the
@@ -152,24 +144,20 @@ class ListCompaniesRequest(proto.Message):
jobs are returned.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- page_token = proto.Field(proto.STRING, number=2)
-
- page_size = proto.Field(proto.INT32, number=3)
-
- require_open_jobs = proto.Field(proto.BOOL, number=4)
+ parent = proto.Field(proto.STRING, number=1,)
+ page_token = proto.Field(proto.STRING, number=2,)
+ page_size = proto.Field(proto.INT32, number=3,)
+ require_open_jobs = proto.Field(proto.BOOL, number=4,)
class ListCompaniesResponse(proto.Message):
r"""The List companies response object.
-
Attributes:
- companies (Sequence[~.gct_company.Company]):
+ companies (Sequence[google.cloud.talent_v4beta1.types.Company]):
Companies for the current client.
next_page_token (str):
A token to retrieve the next page of results.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4beta1.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
@@ -181,9 +169,7 @@ def raw_page(self):
companies = proto.RepeatedField(
proto.MESSAGE, number=1, message=gct_company.Company,
)
-
- next_page_token = proto.Field(proto.STRING, number=2)
-
+ next_page_token = proto.Field(proto.STRING, number=2,)
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
diff --git a/google/cloud/talent_v4beta1/types/completion_service.py b/google/cloud/talent_v4beta1/types/completion_service.py
index 69f4882a..7dbd2415 100644
--- a/google/cloud/talent_v4beta1/types/completion_service.py
+++ b/google/cloud/talent_v4beta1/types/completion_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,10 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
@@ -29,7 +26,6 @@
class CompleteQueryRequest(proto.Message):
r"""Auto-complete parameters.
-
Attributes:
parent (str):
Required. Resource name of tenant the completion is
@@ -63,10 +59,10 @@ class CompleteQueryRequest(proto.Message):
If tenant id is unspecified, the default tenant is used, for
example, "projects/foo".
- scope (~.completion_service.CompleteQueryRequest.CompletionScope):
+ scope (google.cloud.talent_v4beta1.types.CompleteQueryRequest.CompletionScope):
The scope of the completion. The defaults is
[CompletionScope.PUBLIC][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionScope.PUBLIC].
- type_ (~.completion_service.CompleteQueryRequest.CompletionType):
+ type_ (google.cloud.talent_v4beta1.types.CompleteQueryRequest.CompletionType):
The completion topic. The default is
[CompletionType.COMBINED][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionType.COMBINED].
"""
@@ -84,58 +80,47 @@ class CompletionType(proto.Enum):
COMPANY_NAME = 2
COMBINED = 3
- parent = proto.Field(proto.STRING, number=1)
-
- query = proto.Field(proto.STRING, number=2)
-
- language_codes = proto.RepeatedField(proto.STRING, number=3)
-
- page_size = proto.Field(proto.INT32, number=4)
-
- company = proto.Field(proto.STRING, number=5)
-
+ parent = proto.Field(proto.STRING, number=1,)
+ query = proto.Field(proto.STRING, number=2,)
+ language_codes = proto.RepeatedField(proto.STRING, number=3,)
+ page_size = proto.Field(proto.INT32, number=4,)
+ company = proto.Field(proto.STRING, number=5,)
scope = proto.Field(proto.ENUM, number=6, enum=CompletionScope,)
-
type_ = proto.Field(proto.ENUM, number=7, enum=CompletionType,)
class CompleteQueryResponse(proto.Message):
r"""Response of auto-complete query.
-
Attributes:
- completion_results (Sequence[~.completion_service.CompleteQueryResponse.CompletionResult]):
+ completion_results (Sequence[google.cloud.talent_v4beta1.types.CompleteQueryResponse.CompletionResult]):
Results of the matching job/company
candidates.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4beta1.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
class CompletionResult(proto.Message):
r"""Resource that represents completion results.
-
Attributes:
suggestion (str):
The suggestion for the query.
- type_ (~.completion_service.CompleteQueryRequest.CompletionType):
+ type_ (google.cloud.talent_v4beta1.types.CompleteQueryRequest.CompletionType):
The completion topic.
image_uri (str):
The URI of the company image for
[COMPANY_NAME][google.cloud.talent.v4beta1.CompleteQueryRequest.CompletionType.COMPANY_NAME].
"""
- suggestion = proto.Field(proto.STRING, number=1)
-
+ suggestion = proto.Field(proto.STRING, number=1,)
type_ = proto.Field(
proto.ENUM, number=2, enum="CompleteQueryRequest.CompletionType",
)
-
- image_uri = proto.Field(proto.STRING, number=3)
+ image_uri = proto.Field(proto.STRING, number=3,)
completion_results = proto.RepeatedField(
proto.MESSAGE, number=1, message=CompletionResult,
)
-
metadata = proto.Field(proto.MESSAGE, number=2, message=common.ResponseMetadata,)
diff --git a/google/cloud/talent_v4beta1/types/event.py b/google/cloud/talent_v4beta1/types/event.py
index 4583b654..006e44e7 100644
--- a/google/cloud/talent_v4beta1/types/event.py
+++ b/google/cloud/talent_v4beta1/types/event.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,11 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -45,13 +42,13 @@ class ClientEvent(proto.Message):
event_id (str):
Required. A unique identifier, generated by
the client application.
- create_time (~.timestamp.Timestamp):
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
Required. The timestamp of the event.
- job_event (~.event.JobEvent):
+ job_event (google.cloud.talent_v4beta1.types.JobEvent):
An event issued when a job seeker interacts
with the application that implements Cloud
Talent Solution.
- profile_event (~.event.ProfileEvent):
+ profile_event (google.cloud.talent_v4beta1.types.ProfileEvent):
An event issued when a profile searcher
interacts with the application that implements
Cloud Talent Solution.
@@ -61,19 +58,14 @@ class ClientEvent(proto.Message):
profile was bookmarked.
"""
- request_id = proto.Field(proto.STRING, number=1)
-
- event_id = proto.Field(proto.STRING, number=2)
-
- create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,)
-
+ request_id = proto.Field(proto.STRING, number=1,)
+ event_id = proto.Field(proto.STRING, number=2,)
+ create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,)
job_event = proto.Field(proto.MESSAGE, number=5, oneof="event", message="JobEvent",)
-
profile_event = proto.Field(
proto.MESSAGE, number=6, oneof="event", message="ProfileEvent",
)
-
- event_notes = proto.Field(proto.STRING, number=9)
+ event_notes = proto.Field(proto.STRING, number=9,)
class JobEvent(proto.Message):
@@ -81,7 +73,7 @@ class JobEvent(proto.Message):
application that implements Cloud Talent Solution.
Attributes:
- type_ (~.event.JobEvent.JobEventType):
+ type_ (google.cloud.talent_v4beta1.types.JobEvent.JobEventType):
Required. The type of the event (see
[JobEventType][google.cloud.talent.v4beta1.JobEvent.JobEventType]).
jobs (Sequence[str]):
@@ -128,10 +120,8 @@ class JobEventType(proto.Enum):
INTERVIEW_GRANTED = 15
type_ = proto.Field(proto.ENUM, number=1, enum=JobEventType,)
-
- jobs = proto.RepeatedField(proto.STRING, number=2)
-
- profile = proto.Field(proto.STRING, number=3)
+ jobs = proto.RepeatedField(proto.STRING, number=2,)
+ profile = proto.Field(proto.STRING, number=3,)
class ProfileEvent(proto.Message):
@@ -139,7 +129,7 @@ class ProfileEvent(proto.Message):
application that implements Cloud Talent Solution.
Attributes:
- type_ (~.event.ProfileEvent.ProfileEventType):
+ type_ (google.cloud.talent_v4beta1.types.ProfileEvent.ProfileEventType):
Required. Type of event.
profiles (Sequence[str]):
Required. The [profile
@@ -169,10 +159,8 @@ class ProfileEventType(proto.Enum):
BOOKMARK = 3
type_ = proto.Field(proto.ENUM, number=1, enum=ProfileEventType,)
-
- profiles = proto.RepeatedField(proto.STRING, number=2)
-
- jobs = proto.RepeatedField(proto.STRING, number=6)
+ profiles = proto.RepeatedField(proto.STRING, number=2,)
+ jobs = proto.RepeatedField(proto.STRING, number=6,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4beta1/types/event_service.py b/google/cloud/talent_v4beta1/types/event_service.py
index dad4a639..71bc911b 100644
--- a/google/cloud/talent_v4beta1/types/event_service.py
+++ b/google/cloud/talent_v4beta1/types/event_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,10 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import event
@@ -28,7 +25,6 @@
class CreateClientEventRequest(proto.Message):
r"""The report event request.
-
Attributes:
parent (str):
Required. Resource name of the tenant under which the event
@@ -38,14 +34,13 @@ class CreateClientEventRequest(proto.Message):
for example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created, for example,
"projects/foo".
- client_event (~.event.ClientEvent):
+ client_event (google.cloud.talent_v4beta1.types.ClientEvent):
Required. Events issued when end user
interacts with customer's application that uses
Cloud Talent Solution.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
client_event = proto.Field(proto.MESSAGE, number=2, message=event.ClientEvent,)
diff --git a/google/cloud/talent_v4beta1/types/filters.py b/google/cloud/talent_v4beta1/types/filters.py
index 48d631b4..7a90f064 100644
--- a/google/cloud/talent_v4beta1/types/filters.py
+++ b/google/cloud/talent_v4beta1/types/filters.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,17 +13,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
-from google.protobuf import duration_pb2 as duration # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import timeofday_pb2 as timeofday # type: ignore
+from google.protobuf import duration_pb2 # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import timeofday_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -53,7 +50,6 @@
class JobQuery(proto.Message):
r"""The query required to perform a search query.
-
Attributes:
query (str):
The query string that matches against the job
@@ -90,7 +86,7 @@ class JobQuery(proto.Message):
example, "projects/foo/companies/bar".
At most 20 company filters are allowed.
- location_filters (Sequence[~.filters.LocationFilter]):
+ location_filters (Sequence[google.cloud.talent_v4beta1.types.LocationFilter]):
The location filter specifies geo-regions containing the
jobs to search against. See
[LocationFilter][google.cloud.talent.v4beta1.LocationFilter]
@@ -108,7 +104,7 @@ class JobQuery(proto.Message):
locations.
At most 5 location filters are allowed.
- job_categories (Sequence[~.common.JobCategory]):
+ job_categories (Sequence[google.cloud.talent_v4beta1.types.JobCategory]):
The category filter specifies the categories of jobs to
search against. See
[JobCategory][google.cloud.talent.v4beta1.JobCategory] for
@@ -119,7 +115,7 @@ class JobQuery(proto.Message):
If multiple values are specified, jobs from any of the
specified categories are searched against.
- commute_filter (~.filters.CommuteFilter):
+ commute_filter (google.cloud.talent_v4beta1.types.CommuteFilter):
Allows filtering jobs by commute time with different travel
methods (for example, driving or public transit).
@@ -143,7 +139,7 @@ class JobQuery(proto.Message):
companies.
At most 20 company display name filters are allowed.
- compensation_filter (~.filters.CompensationFilter):
+ compensation_filter (google.cloud.talent_v4beta1.types.CompensationFilter):
This search filter is applied only to
[Job.compensation_info][google.cloud.talent.v4beta1.Job.compensation_info].
For example, if the filter is specified as "Hourly job with
@@ -182,7 +178,7 @@ class JobQuery(proto.Message):
misspelled query, for example, "enginee" is
corrected to "engineer".
Defaults to false: a spell check is performed.
- employment_types (Sequence[~.common.EmploymentType]):
+ employment_types (Sequence[google.cloud.talent_v4beta1.types.EmploymentType]):
The employment type filter specifies the employment type of
jobs to search against, such as
[EmploymentType.FULL_TIME][google.cloud.talent.v4beta1.EmploymentType.FULL_TIME].
@@ -205,7 +201,7 @@ class JobQuery(proto.Message):
Languages `__.
At most 10 language code filters are allowed.
- publish_time_range (~.common.TimestampRange):
+ publish_time_range (google.cloud.talent_v4beta1.types.TimestampRange):
Jobs published within a range specified by
this filter are searched against.
excluded_jobs (Sequence[str]):
@@ -214,52 +210,38 @@ class JobQuery(proto.Message):
At most 400 excluded job names are allowed.
"""
- query = proto.Field(proto.STRING, number=1)
-
- query_language_code = proto.Field(proto.STRING, number=14)
-
- companies = proto.RepeatedField(proto.STRING, number=2)
-
+ query = proto.Field(proto.STRING, number=1,)
+ query_language_code = proto.Field(proto.STRING, number=14,)
+ companies = proto.RepeatedField(proto.STRING, number=2,)
location_filters = proto.RepeatedField(
proto.MESSAGE, number=3, message="LocationFilter",
)
-
job_categories = proto.RepeatedField(proto.ENUM, number=4, enum=common.JobCategory,)
-
commute_filter = proto.Field(proto.MESSAGE, number=5, message="CommuteFilter",)
-
- company_display_names = proto.RepeatedField(proto.STRING, number=6)
-
+ company_display_names = proto.RepeatedField(proto.STRING, number=6,)
compensation_filter = proto.Field(
proto.MESSAGE, number=7, message="CompensationFilter",
)
-
- custom_attribute_filter = proto.Field(proto.STRING, number=8)
-
- disable_spell_check = proto.Field(proto.BOOL, number=9)
-
+ custom_attribute_filter = proto.Field(proto.STRING, number=8,)
+ disable_spell_check = proto.Field(proto.BOOL, number=9,)
employment_types = proto.RepeatedField(
proto.ENUM, number=10, enum=common.EmploymentType,
)
-
- language_codes = proto.RepeatedField(proto.STRING, number=11)
-
+ language_codes = proto.RepeatedField(proto.STRING, number=11,)
publish_time_range = proto.Field(
proto.MESSAGE, number=12, message=common.TimestampRange,
)
-
- excluded_jobs = proto.RepeatedField(proto.STRING, number=13)
+ excluded_jobs = proto.RepeatedField(proto.STRING, number=13,)
class ProfileQuery(proto.Message):
r"""Filters to apply when performing the search query.
-
Attributes:
query (str):
Keywords to match any text fields of
profiles.
For example, "software engineer in Palo Alto".
- location_filters (Sequence[~.filters.LocationFilter]):
+ location_filters (Sequence[google.cloud.talent_v4beta1.types.LocationFilter]):
The location filter specifies geo-regions containing the
profiles to search against.
@@ -379,7 +361,7 @@ class ProfileQuery(proto.Message):
If
[LocationFilter.distance_in_miles][google.cloud.talent.v4beta1.LocationFilter.distance_in_miles]
is negative, an error is thrown.
- job_title_filters (Sequence[~.filters.JobTitleFilter]):
+ job_title_filters (Sequence[google.cloud.talent_v4beta1.types.JobTitleFilter]):
Job title filter specifies job titles of profiles to match
on.
@@ -396,7 +378,7 @@ class ProfileQuery(proto.Message):
For example, search for profiles with a job title "Product
Manager".
- employer_filters (Sequence[~.filters.EmployerFilter]):
+ employer_filters (Sequence[google.cloud.talent_v4beta1.types.EmployerFilter]):
Employer filter specifies employers of profiles to match on.
If an employer filter isn't specified, profiles with any
@@ -412,7 +394,7 @@ class ProfileQuery(proto.Message):
For example, search for profiles that have working
experience at "Google LLC".
- education_filters (Sequence[~.filters.EducationFilter]):
+ education_filters (Sequence[google.cloud.talent_v4beta1.types.EducationFilter]):
Education filter specifies education of profiles to match
on.
@@ -428,7 +410,7 @@ class ProfileQuery(proto.Message):
the educations.
For example, search for profiles with a master degree.
- skill_filters (Sequence[~.filters.SkillFilter]):
+ skill_filters (Sequence[google.cloud.talent_v4beta1.types.SkillFilter]):
Skill filter specifies skill of profiles to match on.
If a skill filter isn't specified, profiles with any skills
@@ -444,7 +426,7 @@ class ProfileQuery(proto.Message):
For example, search for profiles that have "Java" and
"Python" in skill list.
- work_experience_filter (Sequence[~.filters.WorkExperienceFilter]):
+ work_experience_filter (Sequence[google.cloud.talent_v4beta1.types.WorkExperienceFilter]):
Work experience filter specifies the total
working experience of profiles to match on.
@@ -458,23 +440,23 @@ class ProfileQuery(proto.Message):
For example, search for profiles with 10 years
of work experience.
- time_filters (Sequence[~.filters.TimeFilter]):
+ time_filters (Sequence[google.cloud.talent_v4beta1.types.TimeFilter]):
Time filter specifies the create/update
timestamp of the profiles to match on.
For example, search for profiles created since
"2018-1-1".
- hirable_filter (~.wrappers.BoolValue):
+ hirable_filter (google.protobuf.wrappers_pb2.BoolValue):
The hirable filter specifies the profile's
hirable status to match on.
- application_date_filters (Sequence[~.filters.ApplicationDateFilter]):
+ application_date_filters (Sequence[google.cloud.talent_v4beta1.types.ApplicationDateFilter]):
The application date filters specify
application date ranges to match on.
- application_outcome_notes_filters (Sequence[~.filters.ApplicationOutcomeNotesFilter]):
+ application_outcome_notes_filters (Sequence[google.cloud.talent_v4beta1.types.ApplicationOutcomeNotesFilter]):
The application outcome notes filters specify
the notes for the outcome of the job
application.
- application_job_filters (Sequence[~.filters.ApplicationJobFilter]):
+ application_job_filters (Sequence[google.cloud.talent_v4beta1.types.ApplicationJobFilter]):
The application job filters specify the job
applied for in the application.
custom_attribute_filter (str):
@@ -507,7 +489,7 @@ class ProfileQuery(proto.Message):
Sample Query: (key1 = "TEST" OR LOWER(key1)="test" OR NOT
EMPTY(key1))
- candidate_availability_filter (~.filters.CandidateAvailabilityFilter):
+ candidate_availability_filter (google.cloud.talent_v4beta1.types.CandidateAvailabilityFilter):
Deprecated. Use availability_filters instead.
The candidate availability filter which filters based on
@@ -528,7 +510,7 @@ class ProfileQuery(proto.Message):
signals. Specifically, the intent is NOT to indicate the
candidate's potential qualification / interest / close
ability for a specific job.
- availability_filters (Sequence[~.filters.AvailabilityFilter]):
+ availability_filters (Sequence[google.cloud.talent_v4beta1.types.AvailabilityFilter]):
The availability filter which filters based on
[Profile.availability_signals][google.cloud.talent.v4beta1.Profile.availability_signals].
@@ -548,7 +530,7 @@ class ProfileQuery(proto.Message):
for a
[signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type],
an error is thrown.
- person_name_filters (Sequence[~.filters.PersonNameFilter]):
+ person_name_filters (Sequence[google.cloud.talent_v4beta1.types.PersonNameFilter]):
Person name filter specifies person name of
profiles to match on.
If multiple person name filters are specified,
@@ -559,56 +541,43 @@ class ProfileQuery(proto.Message):
with name "John Smith".
"""
- query = proto.Field(proto.STRING, number=1)
-
+ query = proto.Field(proto.STRING, number=1,)
location_filters = proto.RepeatedField(
proto.MESSAGE, number=2, message="LocationFilter",
)
-
job_title_filters = proto.RepeatedField(
proto.MESSAGE, number=3, message="JobTitleFilter",
)
-
employer_filters = proto.RepeatedField(
proto.MESSAGE, number=4, message="EmployerFilter",
)
-
education_filters = proto.RepeatedField(
proto.MESSAGE, number=5, message="EducationFilter",
)
-
skill_filters = proto.RepeatedField(proto.MESSAGE, number=6, message="SkillFilter",)
-
work_experience_filter = proto.RepeatedField(
proto.MESSAGE, number=7, message="WorkExperienceFilter",
)
-
time_filters = proto.RepeatedField(proto.MESSAGE, number=8, message="TimeFilter",)
-
- hirable_filter = proto.Field(proto.MESSAGE, number=9, message=wrappers.BoolValue,)
-
+ hirable_filter = proto.Field(
+ proto.MESSAGE, number=9, message=wrappers_pb2.BoolValue,
+ )
application_date_filters = proto.RepeatedField(
proto.MESSAGE, number=10, message="ApplicationDateFilter",
)
-
application_outcome_notes_filters = proto.RepeatedField(
proto.MESSAGE, number=11, message="ApplicationOutcomeNotesFilter",
)
-
application_job_filters = proto.RepeatedField(
proto.MESSAGE, number=13, message="ApplicationJobFilter",
)
-
- custom_attribute_filter = proto.Field(proto.STRING, number=15)
-
+ custom_attribute_filter = proto.Field(proto.STRING, number=15,)
candidate_availability_filter = proto.Field(
proto.MESSAGE, number=16, message="CandidateAvailabilityFilter",
)
-
availability_filters = proto.RepeatedField(
proto.MESSAGE, number=18, message="AvailabilityFilter",
)
-
person_name_filters = proto.RepeatedField(
proto.MESSAGE, number=17, message="PersonNameFilter",
)
@@ -616,7 +585,6 @@ class ProfileQuery(proto.Message):
class LocationFilter(proto.Message):
r"""Geographic region of the search.
-
Attributes:
address (str):
The address name, such as "Mountain View" or
@@ -635,7 +603,7 @@ class LocationFilter(proto.Message):
https://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
for details. Example: "CH" for Switzerland. Note that this
filter is not applicable for Profile Search related queries.
- lat_lng (~.latlng.LatLng):
+ lat_lng (google.type.latlng_pb2.LatLng):
The latitude and longitude of the geographic center to
search from. This field is ignored if ``address`` is
provided.
@@ -644,7 +612,7 @@ class LocationFilter(proto.Message):
searched for is identified as a city or smaller. This field
is ignored if the location being searched for is a state or
larger.
- telecommute_preference (~.filters.LocationFilter.TelecommutePreference):
+ telecommute_preference (google.cloud.talent_v4beta1.types.LocationFilter.TelecommutePreference):
Allows the client to return jobs without a set location,
specifically, telecommuting jobs (telecommuting is
considered by the service as a special location.
@@ -682,31 +650,25 @@ class TelecommutePreference(proto.Enum):
TELECOMMUTE_EXCLUDED = 1
TELECOMMUTE_ALLOWED = 2
- address = proto.Field(proto.STRING, number=1)
-
- region_code = proto.Field(proto.STRING, number=2)
-
- lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng.LatLng,)
-
- distance_in_miles = proto.Field(proto.DOUBLE, number=4)
-
+ address = proto.Field(proto.STRING, number=1,)
+ region_code = proto.Field(proto.STRING, number=2,)
+ lat_lng = proto.Field(proto.MESSAGE, number=3, message=latlng_pb2.LatLng,)
+ distance_in_miles = proto.Field(proto.DOUBLE, number=4,)
telecommute_preference = proto.Field(
proto.ENUM, number=5, enum=TelecommutePreference,
)
-
- negated = proto.Field(proto.BOOL, number=6)
+ negated = proto.Field(proto.BOOL, number=6,)
class CompensationFilter(proto.Message):
r"""Filter on job compensation type and amount.
-
Attributes:
- type_ (~.filters.CompensationFilter.FilterType):
+ type_ (google.cloud.talent_v4beta1.types.CompensationFilter.FilterType):
Required. Type of filter.
- units (Sequence[~.common.CompensationInfo.CompensationUnit]):
+ units (Sequence[google.cloud.talent_v4beta1.types.CompensationInfo.CompensationUnit]):
Required. Specify desired ``base compensation entry's``
[CompensationInfo.CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit].
- range_ (~.common.CompensationInfo.CompensationRange):
+ range_ (google.cloud.talent_v4beta1.types.CompensationInfo.CompensationRange):
Compensation range.
include_jobs_with_unspecified_compensation_range (bool):
If set to true, jobs with unspecified
@@ -722,29 +684,27 @@ class FilterType(proto.Enum):
ANNUALIZED_TOTAL_AMOUNT = 4
type_ = proto.Field(proto.ENUM, number=1, enum=FilterType,)
-
units = proto.RepeatedField(
proto.ENUM, number=2, enum=common.CompensationInfo.CompensationUnit,
)
-
range_ = proto.Field(
proto.MESSAGE, number=3, message=common.CompensationInfo.CompensationRange,
)
-
- include_jobs_with_unspecified_compensation_range = proto.Field(proto.BOOL, number=4)
+ include_jobs_with_unspecified_compensation_range = proto.Field(
+ proto.BOOL, number=4,
+ )
class CommuteFilter(proto.Message):
r"""Parameters needed for commute search.
-
Attributes:
- commute_method (~.common.CommuteMethod):
+ commute_method (google.cloud.talent_v4beta1.types.CommuteMethod):
Required. The method of transportation to
calculate the commute time for.
- start_coordinates (~.latlng.LatLng):
+ start_coordinates (google.type.latlng_pb2.LatLng):
Required. The latitude and longitude of the
location to calculate the commute time from.
- travel_duration (~.duration.Duration):
+ travel_duration (google.protobuf.duration_pb2.Duration):
Required. The maximum travel time in seconds. The maximum
allowed value is ``3600s`` (one hour). Format is ``123s``.
allow_imprecise_addresses (bool):
@@ -754,10 +714,10 @@ class CommuteFilter(proto.Message):
used. If this field is set to ``false`` or isn't specified,
only jobs that include street level addresses will be
returned by commute search.
- road_traffic (~.filters.CommuteFilter.RoadTraffic):
+ road_traffic (google.cloud.talent_v4beta1.types.CommuteFilter.RoadTraffic):
Specifies the traffic density to use when
calculating commute time.
- departure_time (~.timeofday.TimeOfDay):
+ departure_time (google.type.timeofday_pb2.TimeOfDay):
The departure time used to calculate traffic impact,
represented as
[google.type.TimeOfDay][google.type.TimeOfDay] in local time
@@ -774,25 +734,24 @@ class RoadTraffic(proto.Enum):
BUSY_HOUR = 2
commute_method = proto.Field(proto.ENUM, number=1, enum=common.CommuteMethod,)
-
- start_coordinates = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,)
-
- travel_duration = proto.Field(proto.MESSAGE, number=3, message=duration.Duration,)
-
- allow_imprecise_addresses = proto.Field(proto.BOOL, number=4)
-
+ start_coordinates = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,)
+ travel_duration = proto.Field(
+ proto.MESSAGE, number=3, message=duration_pb2.Duration,
+ )
+ allow_imprecise_addresses = proto.Field(proto.BOOL, number=4,)
road_traffic = proto.Field(
proto.ENUM, number=5, oneof="traffic_option", enum=RoadTraffic,
)
-
departure_time = proto.Field(
- proto.MESSAGE, number=6, oneof="traffic_option", message=timeofday.TimeOfDay,
+ proto.MESSAGE,
+ number=6,
+ oneof="traffic_option",
+ message=timeofday_pb2.TimeOfDay,
)
class JobTitleFilter(proto.Message):
r"""Job title of the search.
-
Attributes:
job_title (str):
Required. The job title. For example,
@@ -802,14 +761,12 @@ class JobTitleFilter(proto.Message):
profiles matching the filter are excluded.
"""
- job_title = proto.Field(proto.STRING, number=1)
-
- negated = proto.Field(proto.BOOL, number=2)
+ job_title = proto.Field(proto.STRING, number=1,)
+ negated = proto.Field(proto.BOOL, number=2,)
class SkillFilter(proto.Message):
r"""Skill filter of the search.
-
Attributes:
skill (str):
Required. The skill name. For example,
@@ -819,19 +776,17 @@ class SkillFilter(proto.Message):
profiles matching the filter are excluded.
"""
- skill = proto.Field(proto.STRING, number=1)
-
- negated = proto.Field(proto.BOOL, number=2)
+ skill = proto.Field(proto.STRING, number=1,)
+ negated = proto.Field(proto.BOOL, number=2,)
class EmployerFilter(proto.Message):
r"""Employer filter of the search.
-
Attributes:
employer (str):
Required. The name of the employer, for
example "Google", "Alphabet".
- mode (~.filters.EmployerFilter.EmployerFilterMode):
+ mode (google.cloud.talent_v4beta1.types.EmployerFilter.EmployerFilterMode):
Define set of
[EmploymentRecord][google.cloud.talent.v4beta1.EmploymentRecord]s
to search against.
@@ -853,16 +808,13 @@ class EmployerFilterMode(proto.Enum):
CURRENT_EMPLOYMENT_RECORDS_ONLY = 2
PAST_EMPLOYMENT_RECORDS_ONLY = 3
- employer = proto.Field(proto.STRING, number=1)
-
+ employer = proto.Field(proto.STRING, number=1,)
mode = proto.Field(proto.ENUM, number=2, enum=EmployerFilterMode,)
-
- negated = proto.Field(proto.BOOL, number=3)
+ negated = proto.Field(proto.BOOL, number=3,)
class EducationFilter(proto.Message):
r"""Education filter of the search.
-
Attributes:
school (str):
The school name. For example "MIT",
@@ -872,7 +824,7 @@ class EducationFilter(proto.Message):
in
[Degree.fields_of_study][google.cloud.talent.v4beta1.Degree.fields_of_study].
For example "Computer Science", "Mathematics".
- degree_type (~.common.DegreeType):
+ degree_type (google.cloud.talent_v4beta1.types.DegreeType):
Education degree in ISCED code. Each value in
degree covers a specific level of education,
without any expansion to upper nor lower levels
@@ -882,13 +834,10 @@ class EducationFilter(proto.Message):
profiles matching the filter is excluded.
"""
- school = proto.Field(proto.STRING, number=1)
-
- field_of_study = proto.Field(proto.STRING, number=2)
-
+ school = proto.Field(proto.STRING, number=1,)
+ field_of_study = proto.Field(proto.STRING, number=2,)
degree_type = proto.Field(proto.ENUM, number=3, enum=common.DegreeType,)
-
- negated = proto.Field(proto.BOOL, number=6)
+ negated = proto.Field(proto.BOOL, number=6,)
class WorkExperienceFilter(proto.Message):
@@ -901,17 +850,20 @@ class WorkExperienceFilter(proto.Message):
[max_experience][google.cloud.talent.v4beta1.WorkExperienceFilter.max_experience].
Attributes:
- min_experience (~.duration.Duration):
+ min_experience (google.protobuf.duration_pb2.Duration):
The minimum duration of the work experience
(inclusive).
- max_experience (~.duration.Duration):
+ max_experience (google.protobuf.duration_pb2.Duration):
The maximum duration of the work experience
(exclusive).
"""
- min_experience = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,)
-
- max_experience = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,)
+ min_experience = proto.Field(
+ proto.MESSAGE, number=1, message=duration_pb2.Duration,
+ )
+ max_experience = proto.Field(
+ proto.MESSAGE, number=2, message=duration_pb2.Duration,
+ )
class ApplicationDateFilter(proto.Message):
@@ -927,24 +879,22 @@ class ApplicationDateFilter(proto.Message):
are missing.
Attributes:
- start_date (~.date.Date):
+ start_date (google.type.date_pb2.Date):
Start date. If it's missing, The API matches
profiles with application date not after the end
date.
- end_date (~.date.Date):
+ end_date (google.type.date_pb2.Date):
End date. If it's missing, The API matches
profiles with application date not before the
start date.
"""
- start_date = proto.Field(proto.MESSAGE, number=1, message=date.Date,)
-
- end_date = proto.Field(proto.MESSAGE, number=2, message=date.Date,)
+ start_date = proto.Field(proto.MESSAGE, number=1, message=date_pb2.Date,)
+ end_date = proto.Field(proto.MESSAGE, number=2, message=date_pb2.Date,)
class ApplicationOutcomeNotesFilter(proto.Message):
r"""Outcome Notes Filter.
-
Attributes:
outcome_notes (str):
Required. User entered or selected outcome reason. The API
@@ -957,14 +907,12 @@ class ApplicationOutcomeNotesFilter(proto.Message):
matching the outcome reason specified in the filter.
"""
- outcome_notes = proto.Field(proto.STRING, number=1)
-
- negated = proto.Field(proto.BOOL, number=2)
+ outcome_notes = proto.Field(proto.STRING, number=1,)
+ negated = proto.Field(proto.BOOL, number=2,)
class ApplicationJobFilter(proto.Message):
r"""Filter on the job information of Application.
-
Attributes:
job_requisition_id (str):
The job requisition id in the application. The API does an
@@ -985,28 +933,25 @@ class ApplicationJobFilter(proto.Message):
matching the filters.
"""
- job_requisition_id = proto.Field(proto.STRING, number=2)
-
- job_title = proto.Field(proto.STRING, number=3)
-
- negated = proto.Field(proto.BOOL, number=4)
+ job_requisition_id = proto.Field(proto.STRING, number=2,)
+ job_title = proto.Field(proto.STRING, number=3,)
+ negated = proto.Field(proto.BOOL, number=4,)
class TimeFilter(proto.Message):
r"""Filter on create timestamp or update timestamp of profiles.
-
Attributes:
- start_time (~.timestamp.Timestamp):
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
Start timestamp, matching profiles with the
start time. If this field missing, The API
matches profiles with create / update timestamp
before the end timestamp.
- end_time (~.timestamp.Timestamp):
+ end_time (google.protobuf.timestamp_pb2.Timestamp):
End timestamp, matching profiles with the end
time. If this field missing, The API matches
profiles with create / update timestamp after
the start timestamp.
- time_field (~.filters.TimeFilter.TimeField):
+ time_field (google.cloud.talent_v4beta1.types.TimeFilter.TimeField):
Specifies which time field to filter profiles.
Defaults to
@@ -1019,10 +964,8 @@ class TimeField(proto.Enum):
CREATE_TIME = 1
UPDATE_TIME = 2
- start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,)
-
- end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,)
-
+ start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,)
+ end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,)
time_field = proto.Field(proto.ENUM, number=3, enum=TimeField,)
@@ -1036,16 +979,15 @@ class CandidateAvailabilityFilter(proto.Message):
all the potential available profiles.
"""
- negated = proto.Field(proto.BOOL, number=1)
+ negated = proto.Field(proto.BOOL, number=1,)
class AvailabilityFilter(proto.Message):
r"""Filter on availability signals.
-
Attributes:
- signal_type (~.common.AvailabilitySignalType):
+ signal_type (google.cloud.talent_v4beta1.types.AvailabilitySignalType):
Required. Type of signal to apply filter on.
- range_ (~.common.TimestampRange):
+ range_ (google.cloud.talent_v4beta1.types.TimestampRange):
Required. Range of times to filter candidate
signals by.
required (bool):
@@ -1059,15 +1001,12 @@ class AvailabilityFilter(proto.Message):
"""
signal_type = proto.Field(proto.ENUM, number=1, enum=common.AvailabilitySignalType,)
-
range_ = proto.Field(proto.MESSAGE, number=2, message=common.TimestampRange,)
-
- required = proto.Field(proto.BOOL, number=3)
+ required = proto.Field(proto.BOOL, number=3,)
class PersonNameFilter(proto.Message):
r"""Filter on person name.
-
Attributes:
person_name (str):
Required. The person name. For example, "John Smith".
@@ -1079,7 +1018,7 @@ class PersonNameFilter(proto.Message):
[PersonName.formatted_name][google.cloud.talent.v4beta1.PersonName.formatted_name].
"""
- person_name = proto.Field(proto.STRING, number=1)
+ person_name = proto.Field(proto.STRING, number=1,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4beta1/types/histogram.py b/google/cloud/talent_v4beta1/types/histogram.py
index 6c72e53e..c268d634 100644
--- a/google/cloud/talent_v4beta1/types/histogram.py
+++ b/google/cloud/talent_v4beta1/types/histogram.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
@@ -26,7 +24,6 @@
class HistogramQuery(proto.Message):
r"""The histogram request.
-
Attributes:
histogram_query (str):
An expression specifies a histogram request against matching
@@ -39,7 +36,7 @@ class HistogramQuery(proto.Message):
for details about syntax.
"""
- histogram_query = proto.Field(proto.STRING, number=1)
+ histogram_query = proto.Field(proto.STRING, number=1,)
class HistogramQueryResult(proto.Message):
@@ -50,7 +47,7 @@ class HistogramQueryResult(proto.Message):
Attributes:
histogram_query (str):
Requested histogram expression.
- histogram (Sequence[~.gct_histogram.HistogramQueryResult.HistogramEntry]):
+ histogram (Sequence[google.cloud.talent_v4beta1.types.HistogramQueryResult.HistogramEntry]):
A map from the values of the facet associated with distinct
values to the number of matching entries with corresponding
value.
@@ -66,9 +63,8 @@ class HistogramQueryResult(proto.Message):
``0-MAX``.
"""
- histogram_query = proto.Field(proto.STRING, number=1)
-
- histogram = proto.MapField(proto.STRING, proto.INT64, number=2)
+ histogram_query = proto.Field(proto.STRING, number=1,)
+ histogram = proto.MapField(proto.STRING, proto.INT64, number=2,)
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/google/cloud/talent_v4beta1/types/job.py b/google/cloud/talent_v4beta1/types/job.py
index 147fbe55..23cf1080 100644
--- a/google/cloud/talent_v4beta1/types/job.py
+++ b/google/cloud/talent_v4beta1/types/job.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,12 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(package="google.cloud.talent.v4beta1", manifest={"Job",},)
@@ -117,15 +114,15 @@ class Job(proto.Message):
experience.
The maximum number of allowed characters is 500.
- application_info (~.job.Job.ApplicationInfo):
+ application_info (google.cloud.talent_v4beta1.types.Job.ApplicationInfo):
Job application information.
- job_benefits (Sequence[~.common.JobBenefit]):
+ job_benefits (Sequence[google.cloud.talent_v4beta1.types.JobBenefit]):
The benefits included with the job.
- compensation_info (~.common.CompensationInfo):
+ compensation_info (google.cloud.talent_v4beta1.types.CompensationInfo):
Job compensation information (a.k.a. "pay
rate") i.e., the compensation that will paid to
the employee.
- custom_attributes (Sequence[~.job.Job.CustomAttributesEntry]):
+ custom_attributes (Sequence[google.cloud.talent_v4beta1.types.Job.CustomAttributesEntry]):
A map of fields to hold both filterable and non-filterable
custom job attributes that are not covered by the provided
structured fields.
@@ -140,7 +137,7 @@ class Job(proto.Message):
than 255 characters. For unfilterable ``string_values``, the
maximum total size of ``string_values`` across all keys is
50KB.
- degree_types (Sequence[~.common.DegreeType]):
+ degree_types (Sequence[google.cloud.talent_v4beta1.types.DegreeType]):
The desired education degrees for the job,
such as Bachelors, Masters.
department (str):
@@ -148,7 +145,7 @@ class Job(proto.Message):
company with the open position.
The maximum number of allowed characters is 255.
- employment_types (Sequence[~.common.EmploymentType]):
+ employment_types (Sequence[google.cloud.talent_v4beta1.types.EmploymentType]):
The employment type(s) of a job, for example, [full
time][google.cloud.talent.v4beta1.EmploymentType.FULL_TIME]
or [part
@@ -173,7 +170,7 @@ class Job(proto.Message):
is present, detected language code based on
[Job.description][google.cloud.talent.v4beta1.Job.description]
is assigned, otherwise defaults to 'en_US'.
- job_level (~.common.JobLevel):
+ job_level (google.cloud.talent_v4beta1.types.JobLevel):
The experience level associated with the job,
such as "Entry Level".
promotion_value (int):
@@ -208,7 +205,7 @@ class Job(proto.Message):
markup tags.
The maximum number of allowed characters is 10,000.
- posting_region (~.common.PostingRegion):
+ posting_region (google.cloud.talent_v4beta1.types.PostingRegion):
The job
[PostingRegion][google.cloud.talent.v4beta1.PostingRegion]
(for example, state, country) throughout which the job is
@@ -224,7 +221,7 @@ class Job(proto.Message):
[Job.addresses][google.cloud.talent.v4beta1.Job.addresses]
to the same location level as this field is strongly
recommended.
- visibility (~.common.Visibility):
+ visibility (google.cloud.talent_v4beta1.types.Visibility):
Deprecated. The job is only visible to the owner.
The visibility of the job.
@@ -232,21 +229,21 @@ class Job(proto.Message):
Defaults to
[Visibility.ACCOUNT_ONLY][google.cloud.talent.v4beta1.Visibility.ACCOUNT_ONLY]
if not specified.
- job_start_time (~.timestamp.Timestamp):
+ job_start_time (google.protobuf.timestamp_pb2.Timestamp):
The start timestamp of the job in UTC time
zone. Typically this field is used for
contracting engagements. Invalid timestamps are
ignored.
- job_end_time (~.timestamp.Timestamp):
+ job_end_time (google.protobuf.timestamp_pb2.Timestamp):
The end timestamp of the job. Typically this
field is used for contracting engagements.
Invalid timestamps are ignored.
- posting_publish_time (~.timestamp.Timestamp):
+ posting_publish_time (google.protobuf.timestamp_pb2.Timestamp):
The timestamp this job posting was most
recently published. The default value is the
time the request arrives at the server. Invalid
timestamps are ignored.
- posting_expire_time (~.timestamp.Timestamp):
+ posting_expire_time (google.protobuf.timestamp_pb2.Timestamp):
Strongly recommended for the best service experience.
The expiration timestamp of the job. After this timestamp,
@@ -304,25 +301,24 @@ class Job(proto.Message):
or the masks are empty meaning that every field is updated,
the job posting expires after 30 days from the job's last
update time. Otherwise the expiration date isn't updated.
- posting_create_time (~.timestamp.Timestamp):
+ posting_create_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The timestamp when this job
posting was created.
- posting_update_time (~.timestamp.Timestamp):
+ posting_update_time (google.protobuf.timestamp_pb2.Timestamp):
Output only. The timestamp when this job
posting was last updated.
company_display_name (str):
Output only. Display name of the company
listing the job.
- derived_info (~.job.Job.DerivedInfo):
+ derived_info (google.cloud.talent_v4beta1.types.Job.DerivedInfo):
Output only. Derived details about the job
posting.
- processing_options (~.job.Job.ProcessingOptions):
+ processing_options (google.cloud.talent_v4beta1.types.Job.ProcessingOptions):
Options for job processing.
"""
class ApplicationInfo(proto.Message):
r"""Application related details of a job posting.
-
Attributes:
emails (Sequence[str]):
Use this field to specify email address(es)
@@ -346,17 +342,14 @@ class ApplicationInfo(proto.Message):
each entry is 2,000.
"""
- emails = proto.RepeatedField(proto.STRING, number=1)
-
- instruction = proto.Field(proto.STRING, number=2)
-
- uris = proto.RepeatedField(proto.STRING, number=3)
+ emails = proto.RepeatedField(proto.STRING, number=1,)
+ instruction = proto.Field(proto.STRING, number=2,)
+ uris = proto.RepeatedField(proto.STRING, number=3,)
class DerivedInfo(proto.Message):
r"""Derived details about the job posting.
-
Attributes:
- locations (Sequence[~.common.Location]):
+ locations (Sequence[google.cloud.talent_v4beta1.types.Location]):
Structured locations of the job, resolved from
[Job.addresses][google.cloud.talent.v4beta1.Job.addresses].
@@ -364,7 +357,7 @@ class DerivedInfo(proto.Message):
are exactly matched to
[Job.addresses][google.cloud.talent.v4beta1.Job.addresses]
in the same order.
- job_categories (Sequence[~.common.JobCategory]):
+ job_categories (Sequence[google.cloud.talent_v4beta1.types.JobCategory]):
Job categories derived from
[Job.title][google.cloud.talent.v4beta1.Job.title] and
[Job.description][google.cloud.talent.v4beta1.Job.description].
@@ -373,19 +366,17 @@ class DerivedInfo(proto.Message):
locations = proto.RepeatedField(
proto.MESSAGE, number=1, message=common.Location,
)
-
job_categories = proto.RepeatedField(
proto.ENUM, number=3, enum=common.JobCategory,
)
class ProcessingOptions(proto.Message):
r"""Options for job processing.
-
Attributes:
disable_street_address_resolution (bool):
If set to ``true``, the service does not attempt to resolve
a more precise address for the job.
- html_sanitization (~.common.HtmlSanitization):
+ html_sanitization (google.cloud.talent_v4beta1.types.HtmlSanitization):
Option for job HTML content sanitization. Applied fields
are:
@@ -402,84 +393,58 @@ class ProcessingOptions(proto.Message):
[HtmlSanitization.SIMPLE_FORMATTING_ONLY][google.cloud.talent.v4beta1.HtmlSanitization.SIMPLE_FORMATTING_ONLY].
"""
- disable_street_address_resolution = proto.Field(proto.BOOL, number=1)
-
+ disable_street_address_resolution = proto.Field(proto.BOOL, number=1,)
html_sanitization = proto.Field(
proto.ENUM, number=2, enum=common.HtmlSanitization,
)
- name = proto.Field(proto.STRING, number=1)
-
- company = proto.Field(proto.STRING, number=2)
-
- requisition_id = proto.Field(proto.STRING, number=3)
-
- title = proto.Field(proto.STRING, number=4)
-
- description = proto.Field(proto.STRING, number=5)
-
- addresses = proto.RepeatedField(proto.STRING, number=6)
-
+ name = proto.Field(proto.STRING, number=1,)
+ company = proto.Field(proto.STRING, number=2,)
+ requisition_id = proto.Field(proto.STRING, number=3,)
+ title = proto.Field(proto.STRING, number=4,)
+ description = proto.Field(proto.STRING, number=5,)
+ addresses = proto.RepeatedField(proto.STRING, number=6,)
application_info = proto.Field(proto.MESSAGE, number=7, message=ApplicationInfo,)
-
job_benefits = proto.RepeatedField(proto.ENUM, number=8, enum=common.JobBenefit,)
-
compensation_info = proto.Field(
proto.MESSAGE, number=9, message=common.CompensationInfo,
)
-
custom_attributes = proto.MapField(
proto.STRING, proto.MESSAGE, number=10, message=common.CustomAttribute,
)
-
degree_types = proto.RepeatedField(proto.ENUM, number=11, enum=common.DegreeType,)
-
- department = proto.Field(proto.STRING, number=12)
-
+ department = proto.Field(proto.STRING, number=12,)
employment_types = proto.RepeatedField(
proto.ENUM, number=13, enum=common.EmploymentType,
)
-
- incentives = proto.Field(proto.STRING, number=14)
-
- language_code = proto.Field(proto.STRING, number=15)
-
+ incentives = proto.Field(proto.STRING, number=14,)
+ language_code = proto.Field(proto.STRING, number=15,)
job_level = proto.Field(proto.ENUM, number=16, enum=common.JobLevel,)
-
- promotion_value = proto.Field(proto.INT32, number=17)
-
- qualifications = proto.Field(proto.STRING, number=18)
-
- responsibilities = proto.Field(proto.STRING, number=19)
-
+ promotion_value = proto.Field(proto.INT32, number=17,)
+ qualifications = proto.Field(proto.STRING, number=18,)
+ responsibilities = proto.Field(proto.STRING, number=19,)
posting_region = proto.Field(proto.ENUM, number=20, enum=common.PostingRegion,)
-
visibility = proto.Field(proto.ENUM, number=21, enum=common.Visibility,)
-
- job_start_time = proto.Field(proto.MESSAGE, number=22, message=timestamp.Timestamp,)
-
- job_end_time = proto.Field(proto.MESSAGE, number=23, message=timestamp.Timestamp,)
-
+ job_start_time = proto.Field(
+ proto.MESSAGE, number=22, message=timestamp_pb2.Timestamp,
+ )
+ job_end_time = proto.Field(
+ proto.MESSAGE, number=23, message=timestamp_pb2.Timestamp,
+ )
posting_publish_time = proto.Field(
- proto.MESSAGE, number=24, message=timestamp.Timestamp,
+ proto.MESSAGE, number=24, message=timestamp_pb2.Timestamp,
)
-
posting_expire_time = proto.Field(
- proto.MESSAGE, number=25, message=timestamp.Timestamp,
+ proto.MESSAGE, number=25, message=timestamp_pb2.Timestamp,
)
-
posting_create_time = proto.Field(
- proto.MESSAGE, number=26, message=timestamp.Timestamp,
+ proto.MESSAGE, number=26, message=timestamp_pb2.Timestamp,
)
-
posting_update_time = proto.Field(
- proto.MESSAGE, number=27, message=timestamp.Timestamp,
+ proto.MESSAGE, number=27, message=timestamp_pb2.Timestamp,
)
-
- company_display_name = proto.Field(proto.STRING, number=28)
-
+ company_display_name = proto.Field(proto.STRING, number=28,)
derived_info = proto.Field(proto.MESSAGE, number=29, message=DerivedInfo,)
-
processing_options = proto.Field(
proto.MESSAGE, number=30, message=ProcessingOptions,
)
diff --git a/google/cloud/talent_v4beta1/types/job_service.py b/google/cloud/talent_v4beta1/types/job_service.py
index 5cad2836..6ef282c1 100644
--- a/google/cloud/talent_v4beta1/types/job_service.py
+++ b/google/cloud/talent_v4beta1/types/job_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,17 +13,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import filters
from google.cloud.talent_v4beta1.types import histogram
from google.cloud.talent_v4beta1.types import job as gct_job
-from google.protobuf import duration_pb2 as duration # type: ignore
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.rpc import status_pb2 as gr_status # type: ignore
+from google.protobuf import duration_pb2 # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.rpc import status_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -63,7 +60,6 @@ class JobView(proto.Enum):
class CreateJobRequest(proto.Message):
r"""Create job request.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -73,18 +69,16 @@ class CreateJobRequest(proto.Message):
For example, "projects/foo/tenant/bar". If tenant id is
unspecified a default tenant is created. For example,
"projects/foo".
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4beta1.types.Job):
Required. The Job to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
job = proto.Field(proto.MESSAGE, number=2, message=gct_job.Job,)
class GetJobRequest(proto.Message):
r"""Get job request.
-
Attributes:
name (str):
Required. The resource name of the job to retrieve.
@@ -97,16 +91,15 @@ class GetJobRequest(proto.Message):
example, "projects/foo/jobs/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateJobRequest(proto.Message):
r"""Update job request.
-
Attributes:
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4beta1.types.Job):
Required. The Job to be updated.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -121,13 +114,13 @@ class UpdateJobRequest(proto.Message):
"""
job = proto.Field(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteJobRequest(proto.Message):
r"""Delete job request.
-
Attributes:
name (str):
Required. The resource name of the job to be deleted.
@@ -140,12 +133,11 @@ class DeleteJobRequest(proto.Message):
example, "projects/foo/jobs/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class BatchDeleteJobsRequest(proto.Message):
r"""Batch delete jobs request.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -170,14 +162,12 @@ class BatchDeleteJobsRequest(proto.Message):
requisitionId = "req-1".
"""
- parent = proto.Field(proto.STRING, number=1)
-
- filter = proto.Field(proto.STRING, number=2)
+ parent = proto.Field(proto.STRING, number=1,)
+ filter = proto.Field(proto.STRING, number=2,)
class ListJobsRequest(proto.Message):
r"""List jobs request.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -221,35 +211,30 @@ class ListJobsRequest(proto.Message):
maximum allowed page size is 100.
Default is 100 if empty or a number < 1 is specified.
- job_view (~.job_service.JobView):
+ job_view (google.cloud.talent_v4beta1.types.JobView):
The desired job attributes returned for jobs in the search
response. Defaults to
[JobView.JOB_VIEW_FULL][google.cloud.talent.v4beta1.JobView.JOB_VIEW_FULL]
if no value is specified.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- filter = proto.Field(proto.STRING, number=2)
-
- page_token = proto.Field(proto.STRING, number=3)
-
- page_size = proto.Field(proto.INT32, number=4)
-
+ parent = proto.Field(proto.STRING, number=1,)
+ filter = proto.Field(proto.STRING, number=2,)
+ page_token = proto.Field(proto.STRING, number=3,)
+ page_size = proto.Field(proto.INT32, number=4,)
job_view = proto.Field(proto.ENUM, number=5, enum="JobView",)
class ListJobsResponse(proto.Message):
r"""List jobs response.
-
Attributes:
- jobs (Sequence[~.gct_job.Job]):
+ jobs (Sequence[google.cloud.talent_v4beta1.types.Job]):
The Jobs for a given company.
The maximum number of items returned is based on
the limit field provided in the request.
next_page_token (str):
A token to retrieve the next page of results.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4beta1.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
@@ -259,15 +244,12 @@ def raw_page(self):
return self
jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- next_page_token = proto.Field(proto.STRING, number=2)
-
+ next_page_token = proto.Field(proto.STRING, number=2,)
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
class SearchJobsRequest(proto.Message):
r"""The Request body of the ``SearchJobs`` call.
-
Attributes:
parent (str):
Required. The resource name of the tenant to search within.
@@ -276,17 +258,17 @@ class SearchJobsRequest(proto.Message):
For example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
- search_mode (~.job_service.SearchJobsRequest.SearchMode):
+ search_mode (google.cloud.talent_v4beta1.types.SearchJobsRequest.SearchMode):
Mode of a search.
Defaults to
[SearchMode.JOB_SEARCH][google.cloud.talent.v4beta1.SearchJobsRequest.SearchMode.JOB_SEARCH].
- request_metadata (~.common.RequestMetadata):
+ request_metadata (google.cloud.talent_v4beta1.types.RequestMetadata):
Required. The meta information collected about the job
searcher, used to improve the search quality of the service.
The identifiers (such as ``user_id``) are provided by users,
and must be unique and consistent.
- job_query (~.filters.JobQuery):
+ job_query (google.cloud.talent_v4beta1.types.JobQuery):
Query used to search against jobs, such as
keyword, location filters, etc.
enable_broadening (bool):
@@ -307,7 +289,7 @@ class SearchJobsRequest(proto.Message):
Enabling this flag may adversely impact performance.
Defaults to false.
- histogram_queries (Sequence[~.histogram.HistogramQuery]):
+ histogram_queries (Sequence[google.cloud.talent_v4beta1.types.HistogramQuery]):
An expression specifies a histogram request against matching
jobs.
@@ -420,7 +402,7 @@ class SearchJobsRequest(proto.Message):
- ``count(base_compensation, [bucket(1000, 10000), bucket(10000, 100000), bucket(100000, MAX)])``
- ``count(string_custom_attribute["some-string-custom-attribute"])``
- ``count(numeric_custom_attribute["some-numeric-custom-attribute"], [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative"])``
- job_view (~.job_service.JobView):
+ job_view (google.cloud.talent_v4beta1.types.JobView):
The desired job attributes returned for jobs in the search
response. Defaults to
[JobView.JOB_VIEW_SMALL][google.cloud.talent.v4beta1.JobView.JOB_VIEW_SMALL]
@@ -512,7 +494,7 @@ class SearchJobsRequest(proto.Message):
(37.4 feet). Diversification strategy is still applied
unless explicitly disabled in
[diversification_level][google.cloud.talent.v4beta1.SearchJobsRequest.diversification_level].
- diversification_level (~.job_service.SearchJobsRequest.DiversificationLevel):
+ diversification_level (google.cloud.talent_v4beta1.types.SearchJobsRequest.DiversificationLevel):
Controls whether highly similar jobs are returned next to
each other in the search results. Jobs are identified as
highly similar based on their titles, job categories, and
@@ -524,7 +506,7 @@ class SearchJobsRequest(proto.Message):
Defaults to
[DiversificationLevel.SIMPLE][google.cloud.talent.v4beta1.SearchJobsRequest.DiversificationLevel.SIMPLE]
if no value is specified.
- custom_ranking_info (~.job_service.SearchJobsRequest.CustomRankingInfo):
+ custom_ranking_info (google.cloud.talent_v4beta1.types.SearchJobsRequest.CustomRankingInfo):
Controls over how job documents get ranked on
top of existing relevance score (determined by
API algorithm).
@@ -582,7 +564,7 @@ class CustomRankingInfo(proto.Message):
[SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
Attributes:
- importance_level (~.job_service.SearchJobsRequest.CustomRankingInfo.ImportanceLevel):
+ importance_level (google.cloud.talent_v4beta1.types.SearchJobsRequest.CustomRankingInfo.ImportanceLevel):
Required. Controls over how important the score of
[CustomRankingInfo.ranking_expression][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.ranking_expression]
gets applied to job's final ranking position.
@@ -633,63 +615,47 @@ class ImportanceLevel(proto.Enum):
number=1,
enum="SearchJobsRequest.CustomRankingInfo.ImportanceLevel",
)
+ ranking_expression = proto.Field(proto.STRING, number=2,)
- ranking_expression = proto.Field(proto.STRING, number=2)
-
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
search_mode = proto.Field(proto.ENUM, number=2, enum=SearchMode,)
-
request_metadata = proto.Field(
proto.MESSAGE, number=3, message=common.RequestMetadata,
)
-
job_query = proto.Field(proto.MESSAGE, number=4, message=filters.JobQuery,)
-
- enable_broadening = proto.Field(proto.BOOL, number=5)
-
- require_precise_result_size = proto.Field(proto.BOOL, number=6)
-
+ enable_broadening = proto.Field(proto.BOOL, number=5,)
+ require_precise_result_size = proto.Field(proto.BOOL, number=6,)
histogram_queries = proto.RepeatedField(
proto.MESSAGE, number=7, message=histogram.HistogramQuery,
)
-
job_view = proto.Field(proto.ENUM, number=8, enum="JobView",)
-
- offset = proto.Field(proto.INT32, number=9)
-
- page_size = proto.Field(proto.INT32, number=10)
-
- page_token = proto.Field(proto.STRING, number=11)
-
- order_by = proto.Field(proto.STRING, number=12)
-
+ offset = proto.Field(proto.INT32, number=9,)
+ page_size = proto.Field(proto.INT32, number=10,)
+ page_token = proto.Field(proto.STRING, number=11,)
+ order_by = proto.Field(proto.STRING, number=12,)
diversification_level = proto.Field(
proto.ENUM, number=13, enum=DiversificationLevel,
)
-
custom_ranking_info = proto.Field(
proto.MESSAGE, number=14, message=CustomRankingInfo,
)
-
- disable_keyword_match = proto.Field(proto.BOOL, number=16)
+ disable_keyword_match = proto.Field(proto.BOOL, number=16,)
class SearchJobsResponse(proto.Message):
r"""Response for SearchJob method.
-
Attributes:
- matching_jobs (Sequence[~.job_service.SearchJobsResponse.MatchingJob]):
+ matching_jobs (Sequence[google.cloud.talent_v4beta1.types.SearchJobsResponse.MatchingJob]):
The Job entities that match the specified
[SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
- histogram_query_results (Sequence[~.histogram.HistogramQueryResult]):
+ histogram_query_results (Sequence[google.cloud.talent_v4beta1.types.HistogramQueryResult]):
The histogram results that match with specified
[SearchJobsRequest.histogram_queries][google.cloud.talent.v4beta1.SearchJobsRequest.histogram_queries].
next_page_token (str):
The token that specifies the starting
position of the next page of results. This field
is empty if there are no more results.
- location_filters (Sequence[~.common.Location]):
+ location_filters (Sequence[google.cloud.talent_v4beta1.types.Location]):
The location filters that the service applied to the
specified query. If any filters are lat-lng based, the
[Location.location_type][google.cloud.talent.v4beta1.Location.location_type]
@@ -708,7 +674,7 @@ class SearchJobsResponse(proto.Message):
[SearchJobsRequest.require_precise_result_size][google.cloud.talent.v4beta1.SearchJobsRequest.require_precise_result_size]
to ``true``, or if the response is the last page of results.
Otherwise, the value is ``-1``.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4beta1.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
broadened_query_jobs_count (int):
@@ -723,7 +689,7 @@ class SearchJobsResponse(proto.Message):
broadening) query. If this field is non-zero,
subsequent requests with offset after this
result set should contain all broadened results.
- spell_correction (~.common.SpellingCorrection):
+ spell_correction (google.cloud.talent_v4beta1.types.SpellingCorrection):
The spell checking result, and correction.
"""
@@ -732,7 +698,7 @@ class MatchingJob(proto.Message):
[SearchJobsResponse][google.cloud.talent.v4beta1.SearchJobsResponse].
Attributes:
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4beta1.types.Job):
Job resource that matches the specified
[SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
job_summary (str):
@@ -752,31 +718,26 @@ class MatchingJob(proto.Message):
keywords, if available. All HTML tags in the original fields
are stripped when returned in this field, and matching query
keywords are enclosed in HTML bold tags.
- commute_info (~.job_service.SearchJobsResponse.CommuteInfo):
+ commute_info (google.cloud.talent_v4beta1.types.SearchJobsResponse.CommuteInfo):
Commute information which is generated based on specified
[CommuteFilter][google.cloud.talent.v4beta1.CommuteFilter].
"""
job = proto.Field(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- job_summary = proto.Field(proto.STRING, number=2)
-
- job_title_snippet = proto.Field(proto.STRING, number=3)
-
- search_text_snippet = proto.Field(proto.STRING, number=4)
-
+ job_summary = proto.Field(proto.STRING, number=2,)
+ job_title_snippet = proto.Field(proto.STRING, number=3,)
+ search_text_snippet = proto.Field(proto.STRING, number=4,)
commute_info = proto.Field(
proto.MESSAGE, number=5, message="SearchJobsResponse.CommuteInfo",
)
class CommuteInfo(proto.Message):
r"""Commute details related to this job.
-
Attributes:
- job_location (~.common.Location):
+ job_location (google.cloud.talent_v4beta1.types.Location):
Location used as the destination in the
commute calculation.
- travel_duration (~.duration.Duration):
+ travel_duration (google.protobuf.duration_pb2.Duration):
The number of seconds required to travel to
the job location from the query location. A
duration of 0 seconds indicates that the job
@@ -785,9 +746,8 @@ class CommuteInfo(proto.Message):
"""
job_location = proto.Field(proto.MESSAGE, number=1, message=common.Location,)
-
travel_duration = proto.Field(
- proto.MESSAGE, number=2, message=duration.Duration,
+ proto.MESSAGE, number=2, message=duration_pb2.Duration,
)
@property
@@ -795,25 +755,17 @@ def raw_page(self):
return self
matching_jobs = proto.RepeatedField(proto.MESSAGE, number=1, message=MatchingJob,)
-
histogram_query_results = proto.RepeatedField(
proto.MESSAGE, number=2, message=histogram.HistogramQueryResult,
)
-
- next_page_token = proto.Field(proto.STRING, number=3)
-
+ next_page_token = proto.Field(proto.STRING, number=3,)
location_filters = proto.RepeatedField(
proto.MESSAGE, number=4, message=common.Location,
)
-
- estimated_total_size = proto.Field(proto.INT32, number=5)
-
- total_size = proto.Field(proto.INT32, number=6)
-
+ estimated_total_size = proto.Field(proto.INT32, number=5,)
+ total_size = proto.Field(proto.INT32, number=6,)
metadata = proto.Field(proto.MESSAGE, number=7, message=common.ResponseMetadata,)
-
- broadened_query_jobs_count = proto.Field(proto.INT32, number=8)
-
+ broadened_query_jobs_count = proto.Field(proto.INT32, number=8,)
spell_correction = proto.Field(
proto.MESSAGE, number=9, message=common.SpellingCorrection,
)
@@ -821,7 +773,6 @@ def raw_page(self):
class BatchCreateJobsRequest(proto.Message):
r"""Request to create a batch of jobs.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -831,18 +782,16 @@ class BatchCreateJobsRequest(proto.Message):
For example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
- jobs (Sequence[~.gct_job.Job]):
+ jobs (Sequence[google.cloud.talent_v4beta1.types.Job]):
Required. The jobs to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
jobs = proto.RepeatedField(proto.MESSAGE, number=2, message=gct_job.Job,)
class BatchUpdateJobsRequest(proto.Message):
r"""Request to update a batch of jobs.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -852,9 +801,9 @@ class BatchUpdateJobsRequest(proto.Message):
For example, "projects/foo/tenant/bar". If tenant id is
unspecified, a default tenant is created. For example,
"projects/foo".
- jobs (Sequence[~.gct_job.Job]):
+ jobs (Sequence[google.cloud.talent_v4beta1.types.Job]):
Required. The jobs to be updated.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience. Be
aware that it will also increase latency when checking the
status of a batch operation.
@@ -880,11 +829,11 @@ class BatchUpdateJobsRequest(proto.Message):
response.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
jobs = proto.RepeatedField(proto.MESSAGE, number=2, message=gct_job.Job,)
-
- update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask,
+ )
class JobOperationResult(proto.Message):
@@ -897,7 +846,7 @@ class JobOperationResult(proto.Message):
in case of success.
Attributes:
- job_results (Sequence[~.job_service.JobOperationResult.JobResult]):
+ job_results (Sequence[google.cloud.talent_v4beta1.types.JobOperationResult.JobResult]):
List of job mutation results from a batch
mutate operation. It can change until operation
status is FINISHED, FAILED or CANCELLED.
@@ -905,9 +854,8 @@ class JobOperationResult(proto.Message):
class JobResult(proto.Message):
r"""Mutation result of a job.
-
Attributes:
- job (~.gct_job.Job):
+ job (google.cloud.talent_v4beta1.types.Job):
Here [Job][google.cloud.talent.v4beta1.Job] only contains
basic information including
[name][google.cloud.talent.v4beta1.Job.name],
@@ -917,7 +865,7 @@ class JobResult(proto.Message):
[requisition_id][google.cloud.talent.v4beta1.Job.requisition_id],
use getJob method to retrieve detailed information of the
created/updated job.
- status (~.gr_status.Status):
+ status (google.rpc.status_pb2.Status):
The status of the job processed. This field is populated if
the processing of the
[job][google.cloud.talent.v4beta1.JobOperationResult.JobResult.job]
@@ -925,8 +873,7 @@ class JobResult(proto.Message):
"""
job = proto.Field(proto.MESSAGE, number=1, message=gct_job.Job,)
-
- status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,)
+ status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,)
job_results = proto.RepeatedField(proto.MESSAGE, number=1, message=JobResult,)
diff --git a/google/cloud/talent_v4beta1/types/profile.py b/google/cloud/talent_v4beta1/types/profile.py
index 38428498..34e067f3 100644
--- a/google/cloud/talent_v4beta1/types/profile.py
+++ b/google/cloud/talent_v4beta1/types/profile.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
-from google.type import postal_address_pb2 as postal_address # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -95,16 +92,16 @@ class Profile(proto.Message):
[group_id][google.cloud.talent.v4beta1.Profile.group_id],
and assign it when the second profile is created, indicating
these two profiles are referring to the same candidate.
- is_hirable (~.wrappers.BoolValue):
+ is_hirable (google.protobuf.wrappers_pb2.BoolValue):
Indicates the hirable status of the
candidate.
- create_time (~.timestamp.Timestamp):
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
The timestamp when the profile was first
created at this source.
- update_time (~.timestamp.Timestamp):
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
The timestamp when the profile was last
updated at this source.
- candidate_update_time (~.timestamp.Timestamp):
+ candidate_update_time (google.protobuf.timestamp_pb2.Timestamp):
The timestamp when the profile was last updated as a result
of a direct or indirect action by a candidate.
@@ -130,7 +127,7 @@ class Profile(proto.Message):
must be greater than or equal to
[resume_update_time][google.cloud.talent.v4beta1.Profile.resume_update_time]
or an error is thrown.
- resume_update_time (~.timestamp.Timestamp):
+ resume_update_time (google.protobuf.timestamp_pb2.Timestamp):
The timestamp when the candidate's resume was added or
updated on the candidate's profile. Whether that resume was
directly uploaded by a candidate, pulled from a 3rd party
@@ -139,13 +136,13 @@ class Profile(proto.Message):
If this field is updated, it's expected that
[resume][google.cloud.talent.v4beta1.Profile.resume] is
provided in the create or update calls.
- resume (~.profile.Resume):
+ resume (google.cloud.talent_v4beta1.types.Resume):
The resume representing this profile.
- person_names (Sequence[~.profile.PersonName]):
+ person_names (Sequence[google.cloud.talent_v4beta1.types.PersonName]):
The names of the candidate this profile
references.
Currently only one person name is supported.
- addresses (Sequence[~.profile.Address]):
+ addresses (Sequence[google.cloud.talent_v4beta1.types.Address]):
The candidate's postal addresses. It's highly recommended to
input this information as accurately as possible to help
improve search quality. Here are some recommendations:
@@ -183,13 +180,13 @@ class Profile(proto.Message):
is CONTACT_INFO_USAGE_UNSPECIFIED and
[Address.current][google.cloud.talent.v4beta1.Address.current]
is false or not set.
- email_addresses (Sequence[~.profile.Email]):
+ email_addresses (Sequence[google.cloud.talent_v4beta1.types.Email]):
The candidate's email addresses.
- phone_numbers (Sequence[~.profile.Phone]):
+ phone_numbers (Sequence[google.cloud.talent_v4beta1.types.Phone]):
The candidate's phone number(s).
- personal_uris (Sequence[~.profile.PersonalUri]):
+ personal_uris (Sequence[google.cloud.talent_v4beta1.types.PersonalUri]):
The candidate's personal URIs.
- additional_contact_info (Sequence[~.profile.AdditionalContactInfo]):
+ additional_contact_info (Sequence[google.cloud.talent_v4beta1.types.AdditionalContactInfo]):
Available contact information besides
[addresses][google.cloud.talent.v4beta1.Profile.addresses],
[email_addresses][google.cloud.talent.v4beta1.Profile.email_addresses],
@@ -197,7 +194,7 @@ class Profile(proto.Message):
and
[personal_uris][google.cloud.talent.v4beta1.Profile.personal_uris].
For example, Hang-out, Skype.
- employment_records (Sequence[~.profile.EmploymentRecord]):
+ employment_records (Sequence[google.cloud.talent_v4beta1.types.EmploymentRecord]):
The employment history records of the candidate. It's highly
recommended to input this information as accurately as
possible to help improve search quality. Here are some
@@ -215,7 +212,7 @@ class Profile(proto.Message):
inferred from user inputs.
The limitation for max number of employment records is 100.
- education_records (Sequence[~.profile.EducationRecord]):
+ education_records (Sequence[google.cloud.talent_v4beta1.types.EducationRecord]):
The education history record of the candidate. It's highly
recommended to input this information as accurately as
possible to help improve search quality. Here are some
@@ -232,25 +229,25 @@ class Profile(proto.Message):
inferred from user inputs.
The limitation for max number of education records is 100.
- skills (Sequence[~.common.Skill]):
+ skills (Sequence[google.cloud.talent_v4beta1.types.Skill]):
The skill set of the candidate. It's highly
recommended to provide as much information as
possible to help improve the search quality.
The limitation for max number of skills is 500.
- activities (Sequence[~.profile.Activity]):
+ activities (Sequence[google.cloud.talent_v4beta1.types.Activity]):
The individual or collaborative activities which the
candidate has participated in, for example, open-source
projects, class assignments that aren't listed in
[employment_records][google.cloud.talent.v4beta1.Profile.employment_records].
The limitation for max number of activities is 50.
- publications (Sequence[~.profile.Publication]):
+ publications (Sequence[google.cloud.talent_v4beta1.types.Publication]):
The publications published by the candidate.
The limitation for max number of publications is
50.
- patents (Sequence[~.profile.Patent]):
+ patents (Sequence[google.cloud.talent_v4beta1.types.Patent]):
The patents acquired by the candidate.
- certifications (Sequence[~.common.Certification]):
+ certifications (Sequence[google.cloud.talent_v4beta1.types.Certification]):
The certifications acquired by the candidate.
applications (Sequence[str]):
Output only. The resource names of the
@@ -258,7 +255,7 @@ class Profile(proto.Message):
assignments (Sequence[str]):
Output only. The resource names of the
candidate's assignments.
- custom_attributes (Sequence[~.profile.Profile.CustomAttributesEntry]):
+ custom_attributes (Sequence[google.cloud.talent_v4beta1.types.Profile.CustomAttributesEntry]):
A map of fields to hold both filterable and non-filterable
custom profile attributes that aren't covered by the
provided structured fields. See
@@ -290,10 +287,10 @@ class Profile(proto.Message):
Output only. Keyword snippet shows how the search result is
related to a search query. This is only returned in
[SearchProfilesResponse][google.cloud.talent.v4beta1.SearchProfilesResponse].
- availability_signals (Sequence[~.profile.AvailabilitySignal]):
+ availability_signals (Sequence[google.cloud.talent_v4beta1.types.AvailabilitySignal]):
Output only. Candidate's availability
signals.
- derived_addresses (Sequence[~.common.Location]):
+ derived_addresses (Sequence[google.cloud.talent_v4beta1.types.Location]):
Output only. Derived locations of the profile, resolved from
[Profile.addresses][google.cloud.talent.v4beta1.Profile.addresses].
@@ -303,84 +300,54 @@ class Profile(proto.Message):
in the same order.
"""
- name = proto.Field(proto.STRING, number=1)
-
- external_id = proto.Field(proto.STRING, number=2)
-
- source = proto.Field(proto.STRING, number=3)
-
- uri = proto.Field(proto.STRING, number=4)
-
- group_id = proto.Field(proto.STRING, number=5)
-
- is_hirable = proto.Field(proto.MESSAGE, number=6, message=wrappers.BoolValue,)
-
- create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,)
-
- update_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,)
-
+ name = proto.Field(proto.STRING, number=1,)
+ external_id = proto.Field(proto.STRING, number=2,)
+ source = proto.Field(proto.STRING, number=3,)
+ uri = proto.Field(proto.STRING, number=4,)
+ group_id = proto.Field(proto.STRING, number=5,)
+ is_hirable = proto.Field(proto.MESSAGE, number=6, message=wrappers_pb2.BoolValue,)
+ create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,)
+ update_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,)
candidate_update_time = proto.Field(
- proto.MESSAGE, number=67, message=timestamp.Timestamp,
+ proto.MESSAGE, number=67, message=timestamp_pb2.Timestamp,
)
-
resume_update_time = proto.Field(
- proto.MESSAGE, number=68, message=timestamp.Timestamp,
+ proto.MESSAGE, number=68, message=timestamp_pb2.Timestamp,
)
-
resume = proto.Field(proto.MESSAGE, number=53, message="Resume",)
-
person_names = proto.RepeatedField(proto.MESSAGE, number=11, message="PersonName",)
-
addresses = proto.RepeatedField(proto.MESSAGE, number=12, message="Address",)
-
email_addresses = proto.RepeatedField(proto.MESSAGE, number=13, message="Email",)
-
phone_numbers = proto.RepeatedField(proto.MESSAGE, number=14, message="Phone",)
-
personal_uris = proto.RepeatedField(
proto.MESSAGE, number=15, message="PersonalUri",
)
-
additional_contact_info = proto.RepeatedField(
proto.MESSAGE, number=16, message="AdditionalContactInfo",
)
-
employment_records = proto.RepeatedField(
proto.MESSAGE, number=17, message="EmploymentRecord",
)
-
education_records = proto.RepeatedField(
proto.MESSAGE, number=18, message="EducationRecord",
)
-
skills = proto.RepeatedField(proto.MESSAGE, number=19, message=common.Skill,)
-
activities = proto.RepeatedField(proto.MESSAGE, number=20, message="Activity",)
-
publications = proto.RepeatedField(proto.MESSAGE, number=21, message="Publication",)
-
patents = proto.RepeatedField(proto.MESSAGE, number=22, message="Patent",)
-
certifications = proto.RepeatedField(
proto.MESSAGE, number=23, message=common.Certification,
)
-
- applications = proto.RepeatedField(proto.STRING, number=47)
-
- assignments = proto.RepeatedField(proto.STRING, number=48)
-
+ applications = proto.RepeatedField(proto.STRING, number=47,)
+ assignments = proto.RepeatedField(proto.STRING, number=48,)
custom_attributes = proto.MapField(
proto.STRING, proto.MESSAGE, number=26, message=common.CustomAttribute,
)
-
- processed = proto.Field(proto.BOOL, number=27)
-
- keyword_snippet = proto.Field(proto.STRING, number=28)
-
+ processed = proto.Field(proto.BOOL, number=27,)
+ keyword_snippet = proto.Field(proto.STRING, number=28,)
availability_signals = proto.RepeatedField(
proto.MESSAGE, number=70, message="AvailabilitySignal",
)
-
derived_addresses = proto.RepeatedField(
proto.MESSAGE, number=64, message=common.Location,
)
@@ -388,14 +355,13 @@ class Profile(proto.Message):
class AvailabilitySignal(proto.Message):
r"""Candidate availability signal.
-
Attributes:
- type_ (~.common.AvailabilitySignalType):
+ type_ (google.cloud.talent_v4beta1.types.AvailabilitySignalType):
Type of signal.
- last_update_time (~.timestamp.Timestamp):
+ last_update_time (google.protobuf.timestamp_pb2.Timestamp):
Timestamp of when the given availability
activity last happened.
- filter_satisfied (~.wrappers.BoolValue):
+ filter_satisfied (google.protobuf.wrappers_pb2.BoolValue):
Indicates if the
[last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time]
is within
@@ -412,17 +378,16 @@ class AvailabilitySignal(proto.Message):
"""
type_ = proto.Field(proto.ENUM, number=1, enum=common.AvailabilitySignalType,)
-
last_update_time = proto.Field(
- proto.MESSAGE, number=2, message=timestamp.Timestamp,
+ proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,
+ )
+ filter_satisfied = proto.Field(
+ proto.MESSAGE, number=3, message=wrappers_pb2.BoolValue,
)
-
- filter_satisfied = proto.Field(proto.MESSAGE, number=3, message=wrappers.BoolValue,)
class Resume(proto.Message):
r"""Resource that represents a resume.
-
Attributes:
structured_resume (str):
Users can create a profile with only this field field, if
@@ -439,7 +404,7 @@ class Resume(proto.Message):
Note that the use of the functionality offered by this field
to extract data from resumes is an Alpha feature and as such
is not covered by any SLA.
- resume_type (~.profile.Resume.ResumeType):
+ resume_type (google.cloud.talent_v4beta1.types.Resume.ResumeType):
The format of
[structured_resume][google.cloud.talent.v4beta1.Resume.structured_resume].
"""
@@ -450,20 +415,18 @@ class ResumeType(proto.Enum):
HRXML = 1
OTHER_RESUME_TYPE = 2
- structured_resume = proto.Field(proto.STRING, number=1)
-
+ structured_resume = proto.Field(proto.STRING, number=1,)
resume_type = proto.Field(proto.ENUM, number=2, enum=ResumeType,)
class PersonName(proto.Message):
r"""Resource that represents the name of a person.
-
Attributes:
formatted_name (str):
A string represents a person's full name. For
example, "Dr. John Smith".
Number of characters allowed is 100.
- structured_name (~.profile.PersonName.PersonStructuredName):
+ structured_name (google.cloud.talent_v4beta1.types.PersonName.PersonStructuredName):
A person's name in a structured way (last
name, first name, suffix, and so on.)
preferred_name (str):
@@ -476,7 +439,6 @@ class PersonName(proto.Message):
class PersonStructuredName(proto.Message):
r"""Resource that represents a person's structured name.
-
Attributes:
given_name (str):
Given/first name.
@@ -513,32 +475,24 @@ class PersonStructuredName(proto.Message):
Number of characters allowed is 20.
"""
- given_name = proto.Field(proto.STRING, number=1)
-
- preferred_name = proto.Field(proto.STRING, number=6)
-
- middle_initial = proto.Field(proto.STRING, number=2)
-
- family_name = proto.Field(proto.STRING, number=3)
-
- suffixes = proto.RepeatedField(proto.STRING, number=4)
-
- prefixes = proto.RepeatedField(proto.STRING, number=5)
-
- formatted_name = proto.Field(proto.STRING, number=1, oneof="person_name")
+ given_name = proto.Field(proto.STRING, number=1,)
+ preferred_name = proto.Field(proto.STRING, number=6,)
+ middle_initial = proto.Field(proto.STRING, number=2,)
+ family_name = proto.Field(proto.STRING, number=3,)
+ suffixes = proto.RepeatedField(proto.STRING, number=4,)
+ prefixes = proto.RepeatedField(proto.STRING, number=5,)
+ formatted_name = proto.Field(proto.STRING, number=1, oneof="person_name",)
structured_name = proto.Field(
proto.MESSAGE, number=2, oneof="person_name", message=PersonStructuredName,
)
-
- preferred_name = proto.Field(proto.STRING, number=3)
+ preferred_name = proto.Field(proto.STRING, number=3,)
class Address(proto.Message):
r"""Resource that represents a address.
-
Attributes:
- usage (~.common.ContactInfoUsage):
+ usage (google.cloud.talent_v4beta1.types.ContactInfoUsage):
The usage of the address. For example,
SCHOOL, WORK, PERSONAL.
unstructured_address (str):
@@ -547,30 +501,29 @@ class Address(proto.Message):
View, CA 94043", "Sunnyvale, California".
Number of characters allowed is 100.
- structured_address (~.postal_address.PostalAddress):
+ structured_address (google.type.postal_address_pb2.PostalAddress):
Structured address that contains street
address, city, state, country, and so on.
- current (~.wrappers.BoolValue):
+ current (google.protobuf.wrappers_pb2.BoolValue):
Indicates if it's the person's current
address.
"""
usage = proto.Field(proto.ENUM, number=1, enum=common.ContactInfoUsage,)
-
- unstructured_address = proto.Field(proto.STRING, number=2, oneof="address")
-
+ unstructured_address = proto.Field(proto.STRING, number=2, oneof="address",)
structured_address = proto.Field(
- proto.MESSAGE, number=3, oneof="address", message=postal_address.PostalAddress,
+ proto.MESSAGE,
+ number=3,
+ oneof="address",
+ message=postal_address_pb2.PostalAddress,
)
-
- current = proto.Field(proto.MESSAGE, number=4, message=wrappers.BoolValue,)
+ current = proto.Field(proto.MESSAGE, number=4, message=wrappers_pb2.BoolValue,)
class Email(proto.Message):
r"""Resource that represents a person's email address.
-
Attributes:
- usage (~.common.ContactInfoUsage):
+ usage (google.cloud.talent_v4beta1.types.ContactInfoUsage):
The usage of the email address. For example,
SCHOOL, WORK, PERSONAL.
email_address (str):
@@ -579,18 +532,16 @@ class Email(proto.Message):
"""
usage = proto.Field(proto.ENUM, number=1, enum=common.ContactInfoUsage,)
-
- email_address = proto.Field(proto.STRING, number=2)
+ email_address = proto.Field(proto.STRING, number=2,)
class Phone(proto.Message):
r"""Resource that represents a person's telephone number.
-
Attributes:
- usage (~.common.ContactInfoUsage):
+ usage (google.cloud.talent_v4beta1.types.ContactInfoUsage):
The usage of the phone. For example, SCHOOL,
WORK, PERSONAL.
- type_ (~.profile.Phone.PhoneType):
+ type_ (google.cloud.talent_v4beta1.types.Phone.PhoneType):
The phone type. For example, LANDLINE,
MOBILE, FAX.
number (str):
@@ -622,24 +573,20 @@ class PhoneType(proto.Enum):
MOBILE_OR_LANDLINE = 9
usage = proto.Field(proto.ENUM, number=1, enum=common.ContactInfoUsage,)
-
type_ = proto.Field(proto.ENUM, number=2, enum=PhoneType,)
-
- number = proto.Field(proto.STRING, number=3)
-
- when_available = proto.Field(proto.STRING, number=4)
+ number = proto.Field(proto.STRING, number=3,)
+ when_available = proto.Field(proto.STRING, number=4,)
class PersonalUri(proto.Message):
r"""Resource that represents a valid URI for a personal use.
-
Attributes:
uri (str):
The personal URI.
Number of characters allowed is 4,000.
"""
- uri = proto.Field(proto.STRING, number=1)
+ uri = proto.Field(proto.STRING, number=1,)
class AdditionalContactInfo(proto.Message):
@@ -647,7 +594,7 @@ class AdditionalContactInfo(proto.Message):
phone, email, URI and addresses.
Attributes:
- usage (~.common.ContactInfoUsage):
+ usage (google.cloud.talent_v4beta1.types.ContactInfoUsage):
The usage of this contact method. For
example, SCHOOL, WORK, PERSONAL.
name (str):
@@ -661,19 +608,16 @@ class AdditionalContactInfo(proto.Message):
"""
usage = proto.Field(proto.ENUM, number=1, enum=common.ContactInfoUsage,)
-
- name = proto.Field(proto.STRING, number=2)
-
- contact_id = proto.Field(proto.STRING, number=3)
+ name = proto.Field(proto.STRING, number=2,)
+ contact_id = proto.Field(proto.STRING, number=3,)
class EmploymentRecord(proto.Message):
r"""Resource that represents an employment record of a candidate.
-
Attributes:
- start_date (~.date.Date):
+ start_date (google.type.date_pb2.Date):
Start date of the employment.
- end_date (~.date.Date):
+ end_date (google.type.date_pb2.Date):
End date of the employment.
employer_name (str):
The name of the employer
@@ -685,7 +629,7 @@ class EmploymentRecord(proto.Message):
For example, division, department, client, and
so on.
Number of characters allowed is 100.
- address (~.profile.Address):
+ address (google.cloud.talent_v4beta1.types.Address):
The physical address of the employer.
job_title (str):
The job title of the employment.
@@ -695,11 +639,11 @@ class EmploymentRecord(proto.Message):
job_description (str):
The description of job content.
Number of characters allowed is 100,000.
- is_supervisor (~.wrappers.BoolValue):
+ is_supervisor (google.protobuf.wrappers_pb2.BoolValue):
If the jobs is a supervisor position.
- is_self_employed (~.wrappers.BoolValue):
+ is_self_employed (google.protobuf.wrappers_pb2.BoolValue):
If this employment is self-employed.
- is_current (~.wrappers.BoolValue):
+ is_current (google.protobuf.wrappers_pb2.BoolValue):
If this employment is current.
job_title_snippet (str):
Output only. The job title snippet shows how the
@@ -721,42 +665,33 @@ class EmploymentRecord(proto.Message):
isn't related to the search query.
"""
- start_date = proto.Field(proto.MESSAGE, number=1, message=date.Date,)
-
- end_date = proto.Field(proto.MESSAGE, number=2, message=date.Date,)
-
- employer_name = proto.Field(proto.STRING, number=3)
-
- division_name = proto.Field(proto.STRING, number=4)
-
+ start_date = proto.Field(proto.MESSAGE, number=1, message=date_pb2.Date,)
+ end_date = proto.Field(proto.MESSAGE, number=2, message=date_pb2.Date,)
+ employer_name = proto.Field(proto.STRING, number=3,)
+ division_name = proto.Field(proto.STRING, number=4,)
address = proto.Field(proto.MESSAGE, number=5, message="Address",)
-
- job_title = proto.Field(proto.STRING, number=6)
-
- job_description = proto.Field(proto.STRING, number=7)
-
- is_supervisor = proto.Field(proto.MESSAGE, number=8, message=wrappers.BoolValue,)
-
- is_self_employed = proto.Field(proto.MESSAGE, number=9, message=wrappers.BoolValue,)
-
- is_current = proto.Field(proto.MESSAGE, number=10, message=wrappers.BoolValue,)
-
- job_title_snippet = proto.Field(proto.STRING, number=11)
-
- job_description_snippet = proto.Field(proto.STRING, number=12)
-
- employer_name_snippet = proto.Field(proto.STRING, number=13)
+ job_title = proto.Field(proto.STRING, number=6,)
+ job_description = proto.Field(proto.STRING, number=7,)
+ is_supervisor = proto.Field(
+ proto.MESSAGE, number=8, message=wrappers_pb2.BoolValue,
+ )
+ is_self_employed = proto.Field(
+ proto.MESSAGE, number=9, message=wrappers_pb2.BoolValue,
+ )
+ is_current = proto.Field(proto.MESSAGE, number=10, message=wrappers_pb2.BoolValue,)
+ job_title_snippet = proto.Field(proto.STRING, number=11,)
+ job_description_snippet = proto.Field(proto.STRING, number=12,)
+ employer_name_snippet = proto.Field(proto.STRING, number=13,)
class EducationRecord(proto.Message):
r"""Resource that represents an education record of a candidate.
-
Attributes:
- start_date (~.date.Date):
+ start_date (google.type.date_pb2.Date):
The start date of the education.
- end_date (~.date.Date):
+ end_date (google.type.date_pb2.Date):
The end date of the education.
- expected_graduation_date (~.date.Date):
+ expected_graduation_date (google.type.date_pb2.Date):
The expected graduation date if currently
pursuing a degree.
school_name (str):
@@ -764,7 +699,7 @@ class EducationRecord(proto.Message):
For example, "Stanford University", "UC
Berkeley", and so on.
Number of characters allowed is 250.
- address (~.profile.Address):
+ address (google.cloud.talent_v4beta1.types.Address):
The physical address of the education
institution.
degree_description (str):
@@ -772,12 +707,12 @@ class EducationRecord(proto.Message):
For example, "Master of Science in Computer
Science", "B.S in Math".
Number of characters allowed is 100.
- structured_degree (~.profile.Degree):
+ structured_degree (google.cloud.talent_v4beta1.types.Degree):
The structured notation of the degree.
description (str):
The description of the education.
Number of characters allowed is 100,000.
- is_current (~.wrappers.BoolValue):
+ is_current (google.protobuf.wrappers_pb2.BoolValue):
If this education is current.
school_name_snippet (str):
Output only. The school name snippet shows how the
@@ -794,29 +729,21 @@ class EducationRecord(proto.Message):
to the search query.
"""
- start_date = proto.Field(proto.MESSAGE, number=1, message=date.Date,)
-
- end_date = proto.Field(proto.MESSAGE, number=2, message=date.Date,)
-
- expected_graduation_date = proto.Field(proto.MESSAGE, number=3, message=date.Date,)
-
- school_name = proto.Field(proto.STRING, number=4)
-
+ start_date = proto.Field(proto.MESSAGE, number=1, message=date_pb2.Date,)
+ end_date = proto.Field(proto.MESSAGE, number=2, message=date_pb2.Date,)
+ expected_graduation_date = proto.Field(
+ proto.MESSAGE, number=3, message=date_pb2.Date,
+ )
+ school_name = proto.Field(proto.STRING, number=4,)
address = proto.Field(proto.MESSAGE, number=5, message="Address",)
-
- degree_description = proto.Field(proto.STRING, number=6, oneof="degree")
-
+ degree_description = proto.Field(proto.STRING, number=6, oneof="degree",)
structured_degree = proto.Field(
proto.MESSAGE, number=7, oneof="degree", message="Degree",
)
-
- description = proto.Field(proto.STRING, number=8)
-
- is_current = proto.Field(proto.MESSAGE, number=9, message=wrappers.BoolValue,)
-
- school_name_snippet = proto.Field(proto.STRING, number=10)
-
- degree_snippet = proto.Field(proto.STRING, number=11)
+ description = proto.Field(proto.STRING, number=8,)
+ is_current = proto.Field(proto.MESSAGE, number=9, message=wrappers_pb2.BoolValue,)
+ school_name_snippet = proto.Field(proto.STRING, number=10,)
+ degree_snippet = proto.Field(proto.STRING, number=11,)
class Degree(proto.Message):
@@ -824,7 +751,7 @@ class Degree(proto.Message):
candidate.
Attributes:
- degree_type (~.common.DegreeType):
+ degree_type (google.cloud.talent_v4beta1.types.DegreeType):
ISCED degree type.
degree_name (str):
Full Degree name.
@@ -838,10 +765,8 @@ class Degree(proto.Message):
"""
degree_type = proto.Field(proto.ENUM, number=1, enum=common.DegreeType,)
-
- degree_name = proto.Field(proto.STRING, number=2)
-
- fields_of_study = proto.RepeatedField(proto.STRING, number=3)
+ degree_name = proto.Field(proto.STRING, number=2,)
+ fields_of_study = proto.RepeatedField(proto.STRING, number=3,)
class Activity(proto.Message):
@@ -859,9 +784,9 @@ class Activity(proto.Message):
uri (str):
Activity URI.
Number of characters allowed is 4,000.
- create_date (~.date.Date):
+ create_date (google.type.date_pb2.Date):
The first creation date of the activity.
- update_date (~.date.Date):
+ update_date (google.type.date_pb2.Date):
The last update date of the activity.
team_members (Sequence[str]):
A list of team members involved in this
@@ -870,7 +795,7 @@ class Activity(proto.Message):
The limitation for max number of team members is
50.
- skills_used (Sequence[~.common.Skill]):
+ skills_used (Sequence[google.cloud.talent_v4beta1.types.Skill]):
A list of skills used in this activity.
The limitation for max number of skills used is
50.
@@ -895,25 +820,16 @@ class Activity(proto.Message):
are not related to the search query.
"""
- display_name = proto.Field(proto.STRING, number=1)
-
- description = proto.Field(proto.STRING, number=2)
-
- uri = proto.Field(proto.STRING, number=3)
-
- create_date = proto.Field(proto.MESSAGE, number=4, message=date.Date,)
-
- update_date = proto.Field(proto.MESSAGE, number=5, message=date.Date,)
-
- team_members = proto.RepeatedField(proto.STRING, number=6)
-
+ display_name = proto.Field(proto.STRING, number=1,)
+ description = proto.Field(proto.STRING, number=2,)
+ uri = proto.Field(proto.STRING, number=3,)
+ create_date = proto.Field(proto.MESSAGE, number=4, message=date_pb2.Date,)
+ update_date = proto.Field(proto.MESSAGE, number=5, message=date_pb2.Date,)
+ team_members = proto.RepeatedField(proto.STRING, number=6,)
skills_used = proto.RepeatedField(proto.MESSAGE, number=7, message=common.Skill,)
-
- activity_name_snippet = proto.Field(proto.STRING, number=8)
-
- activity_description_snippet = proto.Field(proto.STRING, number=9)
-
- skills_used_snippet = proto.RepeatedField(proto.STRING, number=10)
+ activity_name_snippet = proto.Field(proto.STRING, number=8,)
+ activity_description_snippet = proto.Field(proto.STRING, number=9,)
+ skills_used_snippet = proto.RepeatedField(proto.STRING, number=10,)
class Publication(proto.Message):
@@ -939,7 +855,7 @@ class Publication(proto.Message):
publisher (str):
The publisher of the journal.
Number of characters allowed is 100.
- publication_date (~.date.Date):
+ publication_date (google.type.date_pb2.Date):
The publication date.
publication_type (str):
The publication type.
@@ -949,28 +865,19 @@ class Publication(proto.Message):
Number of characters allowed is 100.
"""
- authors = proto.RepeatedField(proto.STRING, number=1)
-
- title = proto.Field(proto.STRING, number=2)
-
- description = proto.Field(proto.STRING, number=3)
-
- journal = proto.Field(proto.STRING, number=4)
-
- volume = proto.Field(proto.STRING, number=5)
-
- publisher = proto.Field(proto.STRING, number=6)
-
- publication_date = proto.Field(proto.MESSAGE, number=7, message=date.Date,)
-
- publication_type = proto.Field(proto.STRING, number=8)
-
- isbn = proto.Field(proto.STRING, number=9)
+ authors = proto.RepeatedField(proto.STRING, number=1,)
+ title = proto.Field(proto.STRING, number=2,)
+ description = proto.Field(proto.STRING, number=3,)
+ journal = proto.Field(proto.STRING, number=4,)
+ volume = proto.Field(proto.STRING, number=5,)
+ publisher = proto.Field(proto.STRING, number=6,)
+ publication_date = proto.Field(proto.MESSAGE, number=7, message=date_pb2.Date,)
+ publication_type = proto.Field(proto.STRING, number=8,)
+ isbn = proto.Field(proto.STRING, number=9,)
class Patent(proto.Message):
r"""Resource that represents the patent acquired by a candidate.
-
Attributes:
display_name (str):
Name of the patent.
@@ -981,10 +888,10 @@ class Patent(proto.Message):
patent_status (str):
The status of the patent.
Number of characters allowed is 100.
- patent_status_date (~.date.Date):
+ patent_status_date (google.type.date_pb2.Date):
The date the last time the status of the
patent was checked.
- patent_filing_date (~.date.Date):
+ patent_filing_date (google.type.date_pb2.Date):
The date that the patent was filed.
patent_office (str):
The name of the patent office.
@@ -995,26 +902,18 @@ class Patent(proto.Message):
patent_description (str):
The description of the patent.
Number of characters allowed is 100,000.
- skills_used (Sequence[~.common.Skill]):
+ skills_used (Sequence[google.cloud.talent_v4beta1.types.Skill]):
The skills used in this patent.
"""
- display_name = proto.Field(proto.STRING, number=1)
-
- inventors = proto.RepeatedField(proto.STRING, number=2)
-
- patent_status = proto.Field(proto.STRING, number=3)
-
- patent_status_date = proto.Field(proto.MESSAGE, number=4, message=date.Date,)
-
- patent_filing_date = proto.Field(proto.MESSAGE, number=5, message=date.Date,)
-
- patent_office = proto.Field(proto.STRING, number=6)
-
- patent_number = proto.Field(proto.STRING, number=7)
-
- patent_description = proto.Field(proto.STRING, number=8)
-
+ display_name = proto.Field(proto.STRING, number=1,)
+ inventors = proto.RepeatedField(proto.STRING, number=2,)
+ patent_status = proto.Field(proto.STRING, number=3,)
+ patent_status_date = proto.Field(proto.MESSAGE, number=4, message=date_pb2.Date,)
+ patent_filing_date = proto.Field(proto.MESSAGE, number=5, message=date_pb2.Date,)
+ patent_office = proto.Field(proto.STRING, number=6,)
+ patent_number = proto.Field(proto.STRING, number=7,)
+ patent_description = proto.Field(proto.STRING, number=8,)
skills_used = proto.RepeatedField(proto.MESSAGE, number=9, message=common.Skill,)
diff --git a/google/cloud/talent_v4beta1/types/profile_service.py b/google/cloud/talent_v4beta1/types/profile_service.py
index 1214e0ab..b523d1b7 100644
--- a/google/cloud/talent_v4beta1/types/profile_service.py
+++ b/google/cloud/talent_v4beta1/types/profile_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,15 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import filters
from google.cloud.talent_v4beta1.types import histogram
from google.cloud.talent_v4beta1.types import profile as gct_profile
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -43,7 +40,6 @@
class ListProfilesRequest(proto.Message):
r"""List profiles request.
-
Attributes:
parent (str):
Required. The resource name of the tenant under which the
@@ -81,7 +77,7 @@ class ListProfilesRequest(proto.Message):
returned, at most 100.
Default is 100 unless a positive number smaller
than 100 is specified.
- read_mask (~.field_mask.FieldMask):
+ read_mask (google.protobuf.field_mask_pb2.FieldMask):
A field mask to specify the profile fields to be listed in
response. All fields are listed if it is unset.
@@ -90,22 +86,17 @@ class ListProfilesRequest(proto.Message):
- name
"""
- parent = proto.Field(proto.STRING, number=1)
-
- filter = proto.Field(proto.STRING, number=5)
-
- page_token = proto.Field(proto.STRING, number=2)
-
- page_size = proto.Field(proto.INT32, number=3)
-
- read_mask = proto.Field(proto.MESSAGE, number=4, message=field_mask.FieldMask,)
+ parent = proto.Field(proto.STRING, number=1,)
+ filter = proto.Field(proto.STRING, number=5,)
+ page_token = proto.Field(proto.STRING, number=2,)
+ page_size = proto.Field(proto.INT32, number=3,)
+ read_mask = proto.Field(proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask,)
class ListProfilesResponse(proto.Message):
r"""The List profiles response object.
-
Attributes:
- profiles (Sequence[~.gct_profile.Profile]):
+ profiles (Sequence[google.cloud.talent_v4beta1.types.Profile]):
Profiles for the specific tenant.
next_page_token (str):
A token to retrieve the next page of results.
@@ -119,31 +110,27 @@ def raw_page(self):
profiles = proto.RepeatedField(
proto.MESSAGE, number=1, message=gct_profile.Profile,
)
-
- next_page_token = proto.Field(proto.STRING, number=2)
+ next_page_token = proto.Field(proto.STRING, number=2,)
class CreateProfileRequest(proto.Message):
r"""Create profile request.
-
Attributes:
parent (str):
Required. The name of the tenant this profile belongs to.
The format is "projects/{project_id}/tenants/{tenant_id}".
For example, "projects/foo/tenants/bar".
- profile (~.gct_profile.Profile):
+ profile (google.cloud.talent_v4beta1.types.Profile):
Required. The profile to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
profile = proto.Field(proto.MESSAGE, number=2, message=gct_profile.Profile,)
class GetProfileRequest(proto.Message):
r"""Get profile request.
-
Attributes:
name (str):
Required. Resource name of the profile to get.
@@ -153,29 +140,28 @@ class GetProfileRequest(proto.Message):
For example, "projects/foo/tenants/bar/profiles/baz".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateProfileRequest(proto.Message):
r"""Update profile request
-
Attributes:
- profile (~.gct_profile.Profile):
+ profile (google.cloud.talent_v4beta1.types.Profile):
Required. Profile to be updated.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
A field mask to specify the profile fields to
update.
A full update is performed if it is unset.
"""
profile = proto.Field(proto.MESSAGE, number=1, message=gct_profile.Profile,)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteProfileRequest(proto.Message):
r"""Delete profile request.
-
Attributes:
name (str):
Required. Resource name of the profile to be deleted.
@@ -185,25 +171,24 @@ class DeleteProfileRequest(proto.Message):
For example, "projects/foo/tenants/bar/profiles/baz".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class SearchProfilesRequest(proto.Message):
r"""The request body of the ``SearchProfiles`` call.
-
Attributes:
parent (str):
Required. The resource name of the tenant to search within.
The format is "projects/{project_id}/tenants/{tenant_id}".
For example, "projects/foo/tenants/bar".
- request_metadata (~.common.RequestMetadata):
+ request_metadata (google.cloud.talent_v4beta1.types.RequestMetadata):
Required. The meta information collected
about the profile search user. This is used to
improve the search quality of the service. These
values are provided by users, and must be
precise and consistent.
- profile_query (~.filters.ProfileQuery):
+ profile_query (google.cloud.talent_v4beta1.types.ProfileQuery):
Search query to execute. See
[ProfileQuery][google.cloud.talent.v4beta1.ProfileQuery] for
more details.
@@ -273,7 +258,7 @@ class SearchProfilesRequest(proto.Message):
order, sort values case sensitively (based on
ASCII) when the value is set to true. Default
value is case in-sensitive sort (false).
- histogram_queries (Sequence[~.histogram.HistogramQuery]):
+ histogram_queries (Sequence[google.cloud.talent_v4beta1.types.HistogramQuery]):
A list of expressions specifies histogram requests against
matching profiles for
[SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest].
@@ -426,55 +411,43 @@ class SearchProfilesRequest(proto.Message):
longer boolean strings.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
request_metadata = proto.Field(
proto.MESSAGE, number=2, message=common.RequestMetadata,
)
-
profile_query = proto.Field(proto.MESSAGE, number=3, message=filters.ProfileQuery,)
-
- page_size = proto.Field(proto.INT32, number=4)
-
- page_token = proto.Field(proto.STRING, number=5)
-
- offset = proto.Field(proto.INT32, number=6)
-
- disable_spell_check = proto.Field(proto.BOOL, number=7)
-
- order_by = proto.Field(proto.STRING, number=8)
-
- case_sensitive_sort = proto.Field(proto.BOOL, number=9)
-
+ page_size = proto.Field(proto.INT32, number=4,)
+ page_token = proto.Field(proto.STRING, number=5,)
+ offset = proto.Field(proto.INT32, number=6,)
+ disable_spell_check = proto.Field(proto.BOOL, number=7,)
+ order_by = proto.Field(proto.STRING, number=8,)
+ case_sensitive_sort = proto.Field(proto.BOOL, number=9,)
histogram_queries = proto.RepeatedField(
proto.MESSAGE, number=10, message=histogram.HistogramQuery,
)
-
- result_set_id = proto.Field(proto.STRING, number=12)
-
- strict_keywords_search = proto.Field(proto.BOOL, number=13)
+ result_set_id = proto.Field(proto.STRING, number=12,)
+ strict_keywords_search = proto.Field(proto.BOOL, number=13,)
class SearchProfilesResponse(proto.Message):
r"""Response of SearchProfiles method.
-
Attributes:
estimated_total_size (int):
An estimation of the number of profiles that
match the specified query.
This number isn't guaranteed to be accurate.
- spell_correction (~.common.SpellingCorrection):
+ spell_correction (google.cloud.talent_v4beta1.types.SpellingCorrection):
The spell checking result, and correction.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4beta1.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
next_page_token (str):
A token to retrieve the next page of results.
This is empty if there are no more results.
- histogram_query_results (Sequence[~.histogram.HistogramQueryResult]):
+ histogram_query_results (Sequence[google.cloud.talent_v4beta1.types.HistogramQueryResult]):
The histogram results that match with specified
[SearchProfilesRequest.histogram_queries][google.cloud.talent.v4beta1.SearchProfilesRequest.histogram_queries].
- summarized_profiles (Sequence[~.profile_service.SummarizedProfile]):
+ summarized_profiles (Sequence[google.cloud.talent_v4beta1.types.SummarizedProfile]):
The profile entities that match the specified
[SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest].
result_set_id (str):
@@ -487,25 +460,19 @@ class SearchProfilesResponse(proto.Message):
def raw_page(self):
return self
- estimated_total_size = proto.Field(proto.INT64, number=1)
-
+ estimated_total_size = proto.Field(proto.INT64, number=1,)
spell_correction = proto.Field(
proto.MESSAGE, number=2, message=common.SpellingCorrection,
)
-
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
-
- next_page_token = proto.Field(proto.STRING, number=4)
-
+ next_page_token = proto.Field(proto.STRING, number=4,)
histogram_query_results = proto.RepeatedField(
proto.MESSAGE, number=5, message=histogram.HistogramQueryResult,
)
-
summarized_profiles = proto.RepeatedField(
proto.MESSAGE, number=6, message="SummarizedProfile",
)
-
- result_set_id = proto.Field(proto.STRING, number=7)
+ result_set_id = proto.Field(proto.STRING, number=7,)
class SummarizedProfile(proto.Message):
@@ -513,10 +480,10 @@ class SummarizedProfile(proto.Message):
[SearchProfilesResponse][google.cloud.talent.v4beta1.SearchProfilesResponse].
Attributes:
- profiles (Sequence[~.gct_profile.Profile]):
+ profiles (Sequence[google.cloud.talent_v4beta1.types.Profile]):
A list of profiles that are linked by
[Profile.group_id][google.cloud.talent.v4beta1.Profile.group_id].
- summary (~.gct_profile.Profile):
+ summary (google.cloud.talent_v4beta1.types.Profile):
A profile summary shows the profile summary and how the
profile matches the search query.
@@ -539,7 +506,6 @@ class SummarizedProfile(proto.Message):
profiles = proto.RepeatedField(
proto.MESSAGE, number=1, message=gct_profile.Profile,
)
-
summary = proto.Field(proto.MESSAGE, number=2, message=gct_profile.Profile,)
diff --git a/google/cloud/talent_v4beta1/types/tenant.py b/google/cloud/talent_v4beta1/types/tenant.py
index c7d1974d..6924c3aa 100644
--- a/google/cloud/talent_v4beta1/types/tenant.py
+++ b/google/cloud/talent_v4beta1/types/tenant.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,7 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
@@ -43,7 +41,7 @@ class Tenant(proto.Message):
Required. Client side tenant identifier, used
to uniquely identify the tenant.
The maximum number of allowed characters is 255.
- usage_type (~.tenant.Tenant.DataUsageType):
+ usage_type (google.cloud.talent_v4beta1.types.Tenant.DataUsageType):
Indicates whether data owned by this tenant may be used to
provide product improvements across other tenants.
@@ -69,14 +67,11 @@ class DataUsageType(proto.Enum):
AGGREGATED = 1
ISOLATED = 2
- name = proto.Field(proto.STRING, number=1)
-
- external_id = proto.Field(proto.STRING, number=2)
-
+ name = proto.Field(proto.STRING, number=1,)
+ external_id = proto.Field(proto.STRING, number=2,)
usage_type = proto.Field(proto.ENUM, number=3, enum=DataUsageType,)
-
keyword_searchable_profile_custom_attributes = proto.RepeatedField(
- proto.STRING, number=4
+ proto.STRING, number=4,
)
diff --git a/google/cloud/talent_v4beta1/types/tenant_service.py b/google/cloud/talent_v4beta1/types/tenant_service.py
index 505da6f7..67bacd0d 100644
--- a/google/cloud/talent_v4beta1/types/tenant_service.py
+++ b/google/cloud/talent_v4beta1/types/tenant_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,13 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import proto # type: ignore
-
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import tenant as gct_tenant
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
@@ -38,7 +35,6 @@
class CreateTenantRequest(proto.Message):
r"""The Request of the CreateTenant method.
-
Attributes:
parent (str):
Required. Resource name of the project under which the
@@ -46,18 +42,16 @@ class CreateTenantRequest(proto.Message):
The format is "projects/{project_id}", for example,
"projects/foo".
- tenant (~.gct_tenant.Tenant):
+ tenant (google.cloud.talent_v4beta1.types.Tenant):
Required. The tenant to be created.
"""
- parent = proto.Field(proto.STRING, number=1)
-
+ parent = proto.Field(proto.STRING, number=1,)
tenant = proto.Field(proto.MESSAGE, number=2, message=gct_tenant.Tenant,)
class GetTenantRequest(proto.Message):
r"""Request for getting a tenant by name.
-
Attributes:
name (str):
Required. The resource name of the tenant to be retrieved.
@@ -66,17 +60,16 @@ class GetTenantRequest(proto.Message):
for example, "projects/foo/tenants/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class UpdateTenantRequest(proto.Message):
r"""Request for updating a specified tenant.
-
Attributes:
- tenant (~.gct_tenant.Tenant):
+ tenant (google.cloud.talent_v4beta1.types.Tenant):
Required. The tenant resource to replace the
current resource in the system.
- update_mask (~.field_mask.FieldMask):
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
Strongly recommended for the best service experience.
If
@@ -91,13 +84,13 @@ class UpdateTenantRequest(proto.Message):
"""
tenant = proto.Field(proto.MESSAGE, number=1, message=gct_tenant.Tenant,)
-
- update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,)
+ update_mask = proto.Field(
+ proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
+ )
class DeleteTenantRequest(proto.Message):
r"""Request to delete a tenant.
-
Attributes:
name (str):
Required. The resource name of the tenant to be deleted.
@@ -106,12 +99,11 @@ class DeleteTenantRequest(proto.Message):
for example, "projects/foo/tenants/bar".
"""
- name = proto.Field(proto.STRING, number=1)
+ name = proto.Field(proto.STRING, number=1,)
class ListTenantsRequest(proto.Message):
r"""List tenants for which the client has ACL visibility.
-
Attributes:
parent (str):
Required. Resource name of the project under which the
@@ -128,22 +120,19 @@ class ListTenantsRequest(proto.Message):
number is provided.
"""
- parent = proto.Field(proto.STRING, number=1)
-
- page_token = proto.Field(proto.STRING, number=2)
-
- page_size = proto.Field(proto.INT32, number=3)
+ parent = proto.Field(proto.STRING, number=1,)
+ page_token = proto.Field(proto.STRING, number=2,)
+ page_size = proto.Field(proto.INT32, number=3,)
class ListTenantsResponse(proto.Message):
r"""The List tenants response object.
-
Attributes:
- tenants (Sequence[~.gct_tenant.Tenant]):
+ tenants (Sequence[google.cloud.talent_v4beta1.types.Tenant]):
Tenants for the current client.
next_page_token (str):
A token to retrieve the next page of results.
- metadata (~.common.ResponseMetadata):
+ metadata (google.cloud.talent_v4beta1.types.ResponseMetadata):
Additional information for the API
invocation, such as the request tracking id.
"""
@@ -153,9 +142,7 @@ def raw_page(self):
return self
tenants = proto.RepeatedField(proto.MESSAGE, number=1, message=gct_tenant.Tenant,)
-
- next_page_token = proto.Field(proto.STRING, number=2)
-
+ next_page_token = proto.Field(proto.STRING, number=2,)
metadata = proto.Field(proto.MESSAGE, number=3, message=common.ResponseMetadata,)
diff --git a/noxfile.py b/noxfile.py
index 41eeb037..e09739cc 100644
--- a/noxfile.py
+++ b/noxfile.py
@@ -18,6 +18,7 @@
from __future__ import absolute_import
import os
+import pathlib
import shutil
import nox
@@ -30,6 +31,22 @@
SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"]
UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"]
+CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute()
+
+# 'docfx' is excluded since it only needs to run in 'docs-presubmit'
+nox.options.sessions = [
+ "unit",
+ "system",
+ "cover",
+ "lint",
+ "lint_setup_py",
+ "blacken",
+ "docs",
+]
+
+# Error if a python version is missing
+nox.options.error_on_missing_interpreters = True
+
@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint(session):
@@ -45,16 +62,9 @@ def lint(session):
session.run("flake8", "google", "tests")
-@nox.session(python="3.6")
+@nox.session(python=DEFAULT_PYTHON_VERSION)
def blacken(session):
- """Run black.
-
- Format code to uniform standard.
-
- This currently uses Python 3.6 due to the automated Kokoro run of synthtool.
- That run uses an image that doesn't have 3.6 installed. Before updating this
- check the state of the `gcp_ubuntu_config` we use for that Kokoro run.
- """
+ """Run black. Format code to uniform standard."""
session.install(BLACK_VERSION)
session.run(
"black", *BLACK_PATHS,
@@ -70,17 +80,21 @@ 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",
+ constraints_path = str(
+ CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
)
- session.install("-e", ".")
+ session.install("asyncmock", "pytest-asyncio", "-c", constraints_path)
+
+ session.install("mock", "pytest", "pytest-cov", "-c", constraints_path)
+
+ session.install("-e", ".", "-c", constraints_path)
# Run py.test against the unit tests.
session.run(
"py.test",
"--quiet",
+ f"--junitxml=unit_{session.python}_sponge_log.xml",
"--cov=google/cloud",
"--cov=tests/unit",
"--cov-append",
@@ -101,15 +115,18 @@ def unit(session):
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS)
def system(session):
"""Run the system test suite."""
+ constraints_path = str(
+ CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
+ )
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")
+ # Install pyopenssl for mTLS testing.
+ if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true":
+ session.install("pyopenssl")
system_test_exists = os.path.exists(system_test_path)
system_test_folder_exists = os.path.exists(system_test_folder_path)
@@ -122,16 +139,26 @@ 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("-e", ".")
+ session.install("mock", "pytest", "google-cloud-testutils", "-c", constraints_path)
+ session.install("-e", ".", "-c", constraints_path)
# Run py.test against the system tests.
if system_test_exists:
- session.run("py.test", "--quiet", system_test_path, *session.posargs)
+ session.run(
+ "py.test",
+ "--quiet",
+ f"--junitxml=system_{session.python}_sponge_log.xml",
+ system_test_path,
+ *session.posargs,
+ )
if system_test_folder_exists:
- session.run("py.test", "--quiet", system_test_folder_path, *session.posargs)
+ session.run(
+ "py.test",
+ "--quiet",
+ f"--junitxml=system_{session.python}_sponge_log.xml",
+ system_test_folder_path,
+ *session.posargs,
+ )
@nox.session(python=DEFAULT_PYTHON_VERSION)
@@ -142,7 +169,7 @@ def cover(session):
test runs (not system test runs), and then erases coverage data.
"""
session.install("coverage", "pytest-cov")
- session.run("coverage", "report", "--show-missing", "--fail-under=99")
+ session.run("coverage", "report", "--show-missing", "--fail-under=98")
session.run("coverage", "erase")
@@ -152,7 +179,7 @@ def docs(session):
"""Build the docs for this library."""
session.install("-e", ".")
- session.install("sphinx", "alabaster", "recommonmark")
+ session.install("sphinx==4.0.1", "alabaster", "recommonmark")
shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
session.run(
@@ -174,9 +201,9 @@ def docfx(session):
"""Build the docfx yaml files for this library."""
session.install("-e", ".")
- # sphinx-docfx-yaml supports up to sphinx version 1.5.5.
- # https://github.com/docascode/sphinx-docfx-yaml/issues/97
- session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml")
+ session.install(
+ "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml"
+ )
shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
session.run(
diff --git a/synth.py b/owlbot.py
similarity index 69%
rename from synth.py
rename to owlbot.py
index bc3d5083..c62c78aa 100644
--- a/synth.py
+++ b/owlbot.py
@@ -18,29 +18,18 @@
from synthtool import gcp
from synthtool.languages import python
-gapic = gcp.GAPICBazel()
common = gcp.CommonTemplates()
-versions = ["v4beta1", "v4"]
-excludes = ["setup.py", "nox*.py", "README.rst", "docs/conf.py", "docs/index.rst"]
-# ----------------------------------------------------------------------------
-# Generate speech GAPIC layer
-# ----------------------------------------------------------------------------
-for version in versions:
- library = gapic.py_library(
- service="talent",
- version=version,
- bazel_target=f"//google/cloud/talent/{version}:talent-{version}-py",
- include_protos=True
- )
- s.move(library, excludes=excludes)
+default_version = "v4"
-# fix docstring
-s.replace(
- "google/cloud/**/*.py",
- "\[a-zA-Z\]\[a-zA-Z0-9_\]",
- "[a-zA-Z][a-zA-Z0-9\_]"
-)
+for library in s.get_staging_dirs(default_version):
+ # fix docstring
+ s.replace(library / "google/cloud/**/*.py", "\[a-zA-Z\]\[a-zA-Z0-9_\]", "[a-zA-Z][a-zA-Z0-9\_]")
+
+ excludes = ["setup.py", "nox*.py", "README.rst", "docs/conf.py", "docs/index.rst"]
+ s.move(library, excludes=excludes)
+
+s.remove_staging_dirs()
# ----------------------------------------------------------------------------
# Add templated files
@@ -48,7 +37,7 @@
templated_files = common.py_library(
samples=True, # set to True only if there are samples
microgenerator=True,
- cov_level=99,
+ cov_level=98,
)
s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file
diff --git a/renovate.json b/renovate.json
index 4fa94931..c0489556 100644
--- a/renovate.json
+++ b/renovate.json
@@ -1,5 +1,9 @@
{
"extends": [
"config:base", ":preserveSemverRanges"
- ]
+ ],
+ "ignorePaths": [".pre-commit-config.yaml"],
+ "pip_requirements": {
+ "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"]
+ }
}
diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py
index bca0522e..5ff9e1db 100644
--- a/samples/snippets/noxfile.py
+++ b/samples/snippets/noxfile.py
@@ -50,7 +50,10 @@
# to use your own Cloud project.
'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT',
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
-
+ # If you need to use a specific version of pip,
+ # change pip_version_override to the string representation
+ # of the version number, for example, "20.2.4"
+ "pip_version_override": None,
# A dictionary you want to inject into your test. Don't put any
# secrets here. These values will override predefined values.
'envs': {},
@@ -85,7 +88,7 @@ def get_pytest_env_vars() -> Dict[str, str]:
# DO NOT EDIT - automatically generated.
# All versions used to tested samples.
-ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"]
+ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"]
# Any default versions that should be ignored.
IGNORED_VERSIONS = TEST_CONFIG['ignored_versions']
@@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None:
def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None:
+ if TEST_CONFIG["pip_version_override"]:
+ pip_version = TEST_CONFIG["pip_version_override"]
+ session.install(f"pip=={pip_version}")
"""Runs py.test for a particular project."""
if os.path.exists("requirements.txt"):
- session.install("-r", "requirements.txt")
+ if os.path.exists("constraints.txt"):
+ session.install("-r", "requirements.txt", "-c", "constraints.txt")
+ else:
+ session.install("-r", "requirements.txt")
if os.path.exists("requirements-test.txt"):
- session.install("-r", "requirements-test.txt")
+ if os.path.exists("constraints-test.txt"):
+ session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt")
+ else:
+ session.install("-r", "requirements-test.txt")
if INSTALL_LIBRARY_FROM_SOURCE:
session.install("-e", _get_repo_root())
diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt
index 7e460c8c..95ea1e6a 100644
--- a/samples/snippets/requirements-test.txt
+++ b/samples/snippets/requirements-test.txt
@@ -1 +1 @@
-pytest==6.0.1
+pytest==6.2.4
diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt
index 41bc2060..4eb2e4f9 100755
--- a/samples/snippets/requirements.txt
+++ b/samples/snippets/requirements.txt
@@ -1 +1 @@
-google.cloud.talent==2.0.0
\ No newline at end of file
+google.cloud.talent==2.1.0
\ No newline at end of file
diff --git a/scripts/fixup_talent_v4_keywords.py b/scripts/fixup_talent_v4_keywords.py
index 374af579..acd2147d 100644
--- a/scripts/fixup_talent_v4_keywords.py
+++ b/scripts/fixup_talent_v4_keywords.py
@@ -1,6 +1,5 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,7 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import argparse
import os
import libcst as cst
@@ -41,29 +39,28 @@ def partition(
class talentCallTransformer(cst.CSTTransformer):
CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
- 'batch_create_jobs': ('parent', 'jobs', ),
- 'batch_delete_jobs': ('parent', 'names', ),
- 'batch_update_jobs': ('parent', 'jobs', 'update_mask', ),
- 'complete_query': ('tenant', 'query', 'page_size', 'language_codes', 'company', 'scope', 'type_', ),
- 'create_client_event': ('parent', 'client_event', ),
- 'create_company': ('parent', 'company', ),
- 'create_job': ('parent', 'job', ),
- 'create_tenant': ('parent', 'tenant', ),
- 'delete_company': ('name', ),
- 'delete_job': ('name', ),
- 'delete_tenant': ('name', ),
- 'get_company': ('name', ),
- 'get_job': ('name', ),
- 'get_tenant': ('name', ),
- 'list_companies': ('parent', 'page_token', 'page_size', 'require_open_jobs', ),
- 'list_jobs': ('parent', 'filter', 'page_token', 'page_size', 'job_view', ),
- 'list_tenants': ('parent', 'page_token', 'page_size', ),
- 'search_jobs': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'histogram_queries', 'job_view', 'offset', 'max_page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
- 'search_jobs_for_alert': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'histogram_queries', 'job_view', 'offset', 'max_page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
- 'update_company': ('company', 'update_mask', ),
- 'update_job': ('job', 'update_mask', ),
- 'update_tenant': ('tenant', 'update_mask', ),
-
+ 'batch_create_jobs': ('parent', 'jobs', ),
+ 'batch_delete_jobs': ('parent', 'names', ),
+ 'batch_update_jobs': ('parent', 'jobs', 'update_mask', ),
+ 'complete_query': ('tenant', 'query', 'page_size', 'language_codes', 'company', 'scope', 'type_', ),
+ 'create_client_event': ('parent', 'client_event', ),
+ 'create_company': ('parent', 'company', ),
+ 'create_job': ('parent', 'job', ),
+ 'create_tenant': ('parent', 'tenant', ),
+ 'delete_company': ('name', ),
+ 'delete_job': ('name', ),
+ 'delete_tenant': ('name', ),
+ 'get_company': ('name', ),
+ 'get_job': ('name', ),
+ 'get_tenant': ('name', ),
+ 'list_companies': ('parent', 'page_token', 'page_size', 'require_open_jobs', ),
+ 'list_jobs': ('parent', 'filter', 'page_token', 'page_size', 'job_view', ),
+ 'list_tenants': ('parent', 'page_token', 'page_size', ),
+ 'search_jobs': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'histogram_queries', 'job_view', 'offset', 'max_page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
+ 'search_jobs_for_alert': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'histogram_queries', 'job_view', 'offset', 'max_page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
+ 'update_company': ('company', 'update_mask', ),
+ 'update_job': ('job', 'update_mask', ),
+ 'update_tenant': ('tenant', 'update_mask', ),
}
def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
@@ -94,7 +91,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
value=cst.Dict([
cst.DictElement(
cst.SimpleString("'{}'".format(name)),
- cst.Element(value=arg.value)
+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
diff --git a/scripts/fixup_talent_v4beta1_keywords.py b/scripts/fixup_talent_v4beta1_keywords.py
index c4488d02..429343a3 100644
--- a/scripts/fixup_talent_v4beta1_keywords.py
+++ b/scripts/fixup_talent_v4beta1_keywords.py
@@ -1,6 +1,5 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,7 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import argparse
import os
import libcst as cst
@@ -41,40 +39,39 @@ def partition(
class talentCallTransformer(cst.CSTTransformer):
CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
- 'batch_create_jobs': ('parent', 'jobs', ),
- 'batch_delete_jobs': ('parent', 'filter', ),
- 'batch_update_jobs': ('parent', 'jobs', 'update_mask', ),
- 'complete_query': ('parent', 'query', 'page_size', 'language_codes', 'company', 'scope', 'type_', ),
- 'create_application': ('parent', 'application', ),
- 'create_client_event': ('parent', 'client_event', ),
- 'create_company': ('parent', 'company', ),
- 'create_job': ('parent', 'job', ),
- 'create_profile': ('parent', 'profile', ),
- 'create_tenant': ('parent', 'tenant', ),
- 'delete_application': ('name', ),
- 'delete_company': ('name', ),
- 'delete_job': ('name', ),
- 'delete_profile': ('name', ),
- 'delete_tenant': ('name', ),
- 'get_application': ('name', ),
- 'get_company': ('name', ),
- 'get_job': ('name', ),
- 'get_profile': ('name', ),
- 'get_tenant': ('name', ),
- 'list_applications': ('parent', 'page_token', 'page_size', ),
- 'list_companies': ('parent', 'page_token', 'page_size', 'require_open_jobs', ),
- 'list_jobs': ('parent', 'filter', 'page_token', 'page_size', 'job_view', ),
- 'list_profiles': ('parent', 'filter', 'page_token', 'page_size', 'read_mask', ),
- 'list_tenants': ('parent', 'page_token', 'page_size', ),
- 'search_jobs': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'require_precise_result_size', 'histogram_queries', 'job_view', 'offset', 'page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
- 'search_jobs_for_alert': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'require_precise_result_size', 'histogram_queries', 'job_view', 'offset', 'page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
- 'search_profiles': ('parent', 'request_metadata', 'profile_query', 'page_size', 'page_token', 'offset', 'disable_spell_check', 'order_by', 'case_sensitive_sort', 'histogram_queries', 'result_set_id', 'strict_keywords_search', ),
- 'update_application': ('application', 'update_mask', ),
- 'update_company': ('company', 'update_mask', ),
- 'update_job': ('job', 'update_mask', ),
- 'update_profile': ('profile', 'update_mask', ),
- 'update_tenant': ('tenant', 'update_mask', ),
-
+ 'batch_create_jobs': ('parent', 'jobs', ),
+ 'batch_delete_jobs': ('parent', 'filter', ),
+ 'batch_update_jobs': ('parent', 'jobs', 'update_mask', ),
+ 'complete_query': ('parent', 'query', 'page_size', 'language_codes', 'company', 'scope', 'type_', ),
+ 'create_application': ('parent', 'application', ),
+ 'create_client_event': ('parent', 'client_event', ),
+ 'create_company': ('parent', 'company', ),
+ 'create_job': ('parent', 'job', ),
+ 'create_profile': ('parent', 'profile', ),
+ 'create_tenant': ('parent', 'tenant', ),
+ 'delete_application': ('name', ),
+ 'delete_company': ('name', ),
+ 'delete_job': ('name', ),
+ 'delete_profile': ('name', ),
+ 'delete_tenant': ('name', ),
+ 'get_application': ('name', ),
+ 'get_company': ('name', ),
+ 'get_job': ('name', ),
+ 'get_profile': ('name', ),
+ 'get_tenant': ('name', ),
+ 'list_applications': ('parent', 'page_token', 'page_size', ),
+ 'list_companies': ('parent', 'page_token', 'page_size', 'require_open_jobs', ),
+ 'list_jobs': ('parent', 'filter', 'page_token', 'page_size', 'job_view', ),
+ 'list_profiles': ('parent', 'filter', 'page_token', 'page_size', 'read_mask', ),
+ 'list_tenants': ('parent', 'page_token', 'page_size', ),
+ 'search_jobs': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'require_precise_result_size', 'histogram_queries', 'job_view', 'offset', 'page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
+ 'search_jobs_for_alert': ('parent', 'request_metadata', 'search_mode', 'job_query', 'enable_broadening', 'require_precise_result_size', 'histogram_queries', 'job_view', 'offset', 'page_size', 'page_token', 'order_by', 'diversification_level', 'custom_ranking_info', 'disable_keyword_match', ),
+ 'search_profiles': ('parent', 'request_metadata', 'profile_query', 'page_size', 'page_token', 'offset', 'disable_spell_check', 'order_by', 'case_sensitive_sort', 'histogram_queries', 'result_set_id', 'strict_keywords_search', ),
+ 'update_application': ('application', 'update_mask', ),
+ 'update_company': ('company', 'update_mask', ),
+ 'update_job': ('job', 'update_mask', ),
+ 'update_profile': ('profile', 'update_mask', ),
+ 'update_tenant': ('tenant', 'update_mask', ),
}
def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
@@ -105,7 +102,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
value=cst.Dict([
cst.DictElement(
cst.SimpleString("'{}'".format(name)),
- cst.Element(value=arg.value)
+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
diff --git a/setup.py b/setup.py
index 6cd77735..29b768a8 100644
--- a/setup.py
+++ b/setup.py
@@ -22,18 +22,18 @@
name = "google-cloud-talent"
description = "Google Cloud Talent Solution API client library"
-version = "2.1.0"
+version = "2.2.0"
# Should be one of:
# 'Development Status :: 3 - Alpha'
# 'Development Status :: 4 - Beta'
# 'Development Status :: 5 - Production/Stable'
release_status = "Development Status :: 4 - Beta"
dependencies = [
- "google-api-core[grpc] >= 1.22.0, < 2.0.0dev",
- "proto-plus >= 1.4.0",
- "libcst >= 0.2.5",
+ "google-api-core[grpc] >= 1.26.0, <2.0.0dev",
+ "proto-plus >= 1.15.0",
+ "packaging >= 14.3",
]
-extras = {}
+extras = {"libcst": "libcst >= 0.2.5"}
# Setup boilerplate below this line.
diff --git a/synth.metadata b/synth.metadata
deleted file mode 100644
index c2c125ec..00000000
--- a/synth.metadata
+++ /dev/null
@@ -1,303 +0,0 @@
-{
- "sources": [
- {
- "git": {
- "name": ".",
- "remote": "https://github.com/googleapis/python-talent.git",
- "sha": "d95d9bccf6fca2ee08181d3b63572ca1a4b97eb2"
- }
- },
- {
- "git": {
- "name": "googleapis",
- "remote": "https://github.com/googleapis/googleapis.git",
- "sha": "8a6f4d9acb1620af2156b42b37b54eae257b7cad",
- "internalRef": "348696929"
- }
- },
- {
- "git": {
- "name": "synthtool",
- "remote": "https://github.com/googleapis/synthtool.git",
- "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4"
- }
- },
- {
- "git": {
- "name": "synthtool",
- "remote": "https://github.com/googleapis/synthtool.git",
- "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4"
- }
- }
- ],
- "destinations": [
- {
- "client": {
- "source": "googleapis",
- "apiName": "talent",
- "apiVersion": "v4beta1",
- "language": "python",
- "generator": "bazel"
- }
- },
- {
- "client": {
- "source": "googleapis",
- "apiName": "talent",
- "apiVersion": "v4",
- "language": "python",
- "generator": "bazel"
- }
- }
- ],
- "generatedFiles": [
- ".flake8",
- ".github/CONTRIBUTING.md",
- ".github/ISSUE_TEMPLATE/bug_report.md",
- ".github/ISSUE_TEMPLATE/feature_request.md",
- ".github/ISSUE_TEMPLATE/support_request.md",
- ".github/PULL_REQUEST_TEMPLATE.md",
- ".github/release-please.yml",
- ".github/snippet-bot.yml",
- ".gitignore",
- ".kokoro/build.sh",
- ".kokoro/continuous/common.cfg",
- ".kokoro/continuous/continuous.cfg",
- ".kokoro/docker/docs/Dockerfile",
- ".kokoro/docker/docs/fetch_gpg_keys.sh",
- ".kokoro/docs/common.cfg",
- ".kokoro/docs/docs-presubmit.cfg",
- ".kokoro/docs/docs.cfg",
- ".kokoro/populate-secrets.sh",
- ".kokoro/presubmit/common.cfg",
- ".kokoro/presubmit/presubmit.cfg",
- ".kokoro/publish-docs.sh",
- ".kokoro/release.sh",
- ".kokoro/release/common.cfg",
- ".kokoro/release/release.cfg",
- ".kokoro/samples/lint/common.cfg",
- ".kokoro/samples/lint/continuous.cfg",
- ".kokoro/samples/lint/periodic.cfg",
- ".kokoro/samples/lint/presubmit.cfg",
- ".kokoro/samples/python3.6/common.cfg",
- ".kokoro/samples/python3.6/continuous.cfg",
- ".kokoro/samples/python3.6/periodic.cfg",
- ".kokoro/samples/python3.6/presubmit.cfg",
- ".kokoro/samples/python3.7/common.cfg",
- ".kokoro/samples/python3.7/continuous.cfg",
- ".kokoro/samples/python3.7/periodic.cfg",
- ".kokoro/samples/python3.7/presubmit.cfg",
- ".kokoro/samples/python3.8/common.cfg",
- ".kokoro/samples/python3.8/continuous.cfg",
- ".kokoro/samples/python3.8/periodic.cfg",
- ".kokoro/samples/python3.8/presubmit.cfg",
- ".kokoro/test-samples.sh",
- ".kokoro/trampoline.sh",
- ".kokoro/trampoline_v2.sh",
- ".pre-commit-config.yaml",
- ".trampolinerc",
- "CODE_OF_CONDUCT.md",
- "CONTRIBUTING.rst",
- "LICENSE",
- "MANIFEST.in",
- "docs/_static/custom.css",
- "docs/_templates/layout.html",
- "docs/conf.py",
- "docs/multiprocessing.rst",
- "docs/talent_v4/services.rst",
- "docs/talent_v4/types.rst",
- "docs/talent_v4beta1/services.rst",
- "docs/talent_v4beta1/types.rst",
- "google/cloud/talent/__init__.py",
- "google/cloud/talent/py.typed",
- "google/cloud/talent_v4/__init__.py",
- "google/cloud/talent_v4/proto/common.proto",
- "google/cloud/talent_v4/proto/company.proto",
- "google/cloud/talent_v4/proto/company_service.proto",
- "google/cloud/talent_v4/proto/completion_service.proto",
- "google/cloud/talent_v4/proto/event.proto",
- "google/cloud/talent_v4/proto/event_service.proto",
- "google/cloud/talent_v4/proto/filters.proto",
- "google/cloud/talent_v4/proto/histogram.proto",
- "google/cloud/talent_v4/proto/job.proto",
- "google/cloud/talent_v4/proto/job_service.proto",
- "google/cloud/talent_v4/proto/tenant.proto",
- "google/cloud/talent_v4/proto/tenant_service.proto",
- "google/cloud/talent_v4/py.typed",
- "google/cloud/talent_v4/services/__init__.py",
- "google/cloud/talent_v4/services/company_service/__init__.py",
- "google/cloud/talent_v4/services/company_service/async_client.py",
- "google/cloud/talent_v4/services/company_service/client.py",
- "google/cloud/talent_v4/services/company_service/pagers.py",
- "google/cloud/talent_v4/services/company_service/transports/__init__.py",
- "google/cloud/talent_v4/services/company_service/transports/base.py",
- "google/cloud/talent_v4/services/company_service/transports/grpc.py",
- "google/cloud/talent_v4/services/company_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4/services/completion/__init__.py",
- "google/cloud/talent_v4/services/completion/async_client.py",
- "google/cloud/talent_v4/services/completion/client.py",
- "google/cloud/talent_v4/services/completion/transports/__init__.py",
- "google/cloud/talent_v4/services/completion/transports/base.py",
- "google/cloud/talent_v4/services/completion/transports/grpc.py",
- "google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py",
- "google/cloud/talent_v4/services/event_service/__init__.py",
- "google/cloud/talent_v4/services/event_service/async_client.py",
- "google/cloud/talent_v4/services/event_service/client.py",
- "google/cloud/talent_v4/services/event_service/transports/__init__.py",
- "google/cloud/talent_v4/services/event_service/transports/base.py",
- "google/cloud/talent_v4/services/event_service/transports/grpc.py",
- "google/cloud/talent_v4/services/event_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4/services/job_service/__init__.py",
- "google/cloud/talent_v4/services/job_service/async_client.py",
- "google/cloud/talent_v4/services/job_service/client.py",
- "google/cloud/talent_v4/services/job_service/pagers.py",
- "google/cloud/talent_v4/services/job_service/transports/__init__.py",
- "google/cloud/talent_v4/services/job_service/transports/base.py",
- "google/cloud/talent_v4/services/job_service/transports/grpc.py",
- "google/cloud/talent_v4/services/job_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4/services/tenant_service/__init__.py",
- "google/cloud/talent_v4/services/tenant_service/async_client.py",
- "google/cloud/talent_v4/services/tenant_service/client.py",
- "google/cloud/talent_v4/services/tenant_service/pagers.py",
- "google/cloud/talent_v4/services/tenant_service/transports/__init__.py",
- "google/cloud/talent_v4/services/tenant_service/transports/base.py",
- "google/cloud/talent_v4/services/tenant_service/transports/grpc.py",
- "google/cloud/talent_v4/services/tenant_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4/types/__init__.py",
- "google/cloud/talent_v4/types/common.py",
- "google/cloud/talent_v4/types/company.py",
- "google/cloud/talent_v4/types/company_service.py",
- "google/cloud/talent_v4/types/completion_service.py",
- "google/cloud/talent_v4/types/event.py",
- "google/cloud/talent_v4/types/event_service.py",
- "google/cloud/talent_v4/types/filters.py",
- "google/cloud/talent_v4/types/histogram.py",
- "google/cloud/talent_v4/types/job.py",
- "google/cloud/talent_v4/types/job_service.py",
- "google/cloud/talent_v4/types/tenant.py",
- "google/cloud/talent_v4/types/tenant_service.py",
- "google/cloud/talent_v4beta1/__init__.py",
- "google/cloud/talent_v4beta1/proto/application.proto",
- "google/cloud/talent_v4beta1/proto/application_service.proto",
- "google/cloud/talent_v4beta1/proto/batch.proto",
- "google/cloud/talent_v4beta1/proto/common.proto",
- "google/cloud/talent_v4beta1/proto/company.proto",
- "google/cloud/talent_v4beta1/proto/company_service.proto",
- "google/cloud/talent_v4beta1/proto/completion_service.proto",
- "google/cloud/talent_v4beta1/proto/event.proto",
- "google/cloud/talent_v4beta1/proto/event_service.proto",
- "google/cloud/talent_v4beta1/proto/filters.proto",
- "google/cloud/talent_v4beta1/proto/histogram.proto",
- "google/cloud/talent_v4beta1/proto/job.proto",
- "google/cloud/talent_v4beta1/proto/job_service.proto",
- "google/cloud/talent_v4beta1/proto/profile.proto",
- "google/cloud/talent_v4beta1/proto/profile_service.proto",
- "google/cloud/talent_v4beta1/proto/tenant.proto",
- "google/cloud/talent_v4beta1/proto/tenant_service.proto",
- "google/cloud/talent_v4beta1/py.typed",
- "google/cloud/talent_v4beta1/services/__init__.py",
- "google/cloud/talent_v4beta1/services/application_service/__init__.py",
- "google/cloud/talent_v4beta1/services/application_service/async_client.py",
- "google/cloud/talent_v4beta1/services/application_service/client.py",
- "google/cloud/talent_v4beta1/services/application_service/pagers.py",
- "google/cloud/talent_v4beta1/services/application_service/transports/__init__.py",
- "google/cloud/talent_v4beta1/services/application_service/transports/base.py",
- "google/cloud/talent_v4beta1/services/application_service/transports/grpc.py",
- "google/cloud/talent_v4beta1/services/application_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4beta1/services/company_service/__init__.py",
- "google/cloud/talent_v4beta1/services/company_service/async_client.py",
- "google/cloud/talent_v4beta1/services/company_service/client.py",
- "google/cloud/talent_v4beta1/services/company_service/pagers.py",
- "google/cloud/talent_v4beta1/services/company_service/transports/__init__.py",
- "google/cloud/talent_v4beta1/services/company_service/transports/base.py",
- "google/cloud/talent_v4beta1/services/company_service/transports/grpc.py",
- "google/cloud/talent_v4beta1/services/company_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4beta1/services/completion/__init__.py",
- "google/cloud/talent_v4beta1/services/completion/async_client.py",
- "google/cloud/talent_v4beta1/services/completion/client.py",
- "google/cloud/talent_v4beta1/services/completion/transports/__init__.py",
- "google/cloud/talent_v4beta1/services/completion/transports/base.py",
- "google/cloud/talent_v4beta1/services/completion/transports/grpc.py",
- "google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py",
- "google/cloud/talent_v4beta1/services/event_service/__init__.py",
- "google/cloud/talent_v4beta1/services/event_service/async_client.py",
- "google/cloud/talent_v4beta1/services/event_service/client.py",
- "google/cloud/talent_v4beta1/services/event_service/transports/__init__.py",
- "google/cloud/talent_v4beta1/services/event_service/transports/base.py",
- "google/cloud/talent_v4beta1/services/event_service/transports/grpc.py",
- "google/cloud/talent_v4beta1/services/event_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4beta1/services/job_service/__init__.py",
- "google/cloud/talent_v4beta1/services/job_service/async_client.py",
- "google/cloud/talent_v4beta1/services/job_service/client.py",
- "google/cloud/talent_v4beta1/services/job_service/pagers.py",
- "google/cloud/talent_v4beta1/services/job_service/transports/__init__.py",
- "google/cloud/talent_v4beta1/services/job_service/transports/base.py",
- "google/cloud/talent_v4beta1/services/job_service/transports/grpc.py",
- "google/cloud/talent_v4beta1/services/job_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4beta1/services/profile_service/__init__.py",
- "google/cloud/talent_v4beta1/services/profile_service/async_client.py",
- "google/cloud/talent_v4beta1/services/profile_service/client.py",
- "google/cloud/talent_v4beta1/services/profile_service/pagers.py",
- "google/cloud/talent_v4beta1/services/profile_service/transports/__init__.py",
- "google/cloud/talent_v4beta1/services/profile_service/transports/base.py",
- "google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py",
- "google/cloud/talent_v4beta1/services/profile_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4beta1/services/tenant_service/__init__.py",
- "google/cloud/talent_v4beta1/services/tenant_service/async_client.py",
- "google/cloud/talent_v4beta1/services/tenant_service/client.py",
- "google/cloud/talent_v4beta1/services/tenant_service/pagers.py",
- "google/cloud/talent_v4beta1/services/tenant_service/transports/__init__.py",
- "google/cloud/talent_v4beta1/services/tenant_service/transports/base.py",
- "google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py",
- "google/cloud/talent_v4beta1/services/tenant_service/transports/grpc_asyncio.py",
- "google/cloud/talent_v4beta1/types/__init__.py",
- "google/cloud/talent_v4beta1/types/application.py",
- "google/cloud/talent_v4beta1/types/application_service.py",
- "google/cloud/talent_v4beta1/types/batch.py",
- "google/cloud/talent_v4beta1/types/common.py",
- "google/cloud/talent_v4beta1/types/company.py",
- "google/cloud/talent_v4beta1/types/company_service.py",
- "google/cloud/talent_v4beta1/types/completion_service.py",
- "google/cloud/talent_v4beta1/types/event.py",
- "google/cloud/talent_v4beta1/types/event_service.py",
- "google/cloud/talent_v4beta1/types/filters.py",
- "google/cloud/talent_v4beta1/types/histogram.py",
- "google/cloud/talent_v4beta1/types/job.py",
- "google/cloud/talent_v4beta1/types/job_service.py",
- "google/cloud/talent_v4beta1/types/profile.py",
- "google/cloud/talent_v4beta1/types/profile_service.py",
- "google/cloud/talent_v4beta1/types/tenant.py",
- "google/cloud/talent_v4beta1/types/tenant_service.py",
- "mypy.ini",
- "noxfile.py",
- "renovate.json",
- "samples/AUTHORING_GUIDE.md",
- "samples/CONTRIBUTING.md",
- "samples/snippets/noxfile.py",
- "scripts/decrypt-secrets.sh",
- "scripts/fixup_talent_v4_keywords.py",
- "scripts/fixup_talent_v4beta1_keywords.py",
- "scripts/readme-gen/readme_gen.py",
- "scripts/readme-gen/templates/README.tmpl.rst",
- "scripts/readme-gen/templates/auth.tmpl.rst",
- "scripts/readme-gen/templates/auth_api_key.tmpl.rst",
- "scripts/readme-gen/templates/install_deps.tmpl.rst",
- "scripts/readme-gen/templates/install_portaudio.tmpl.rst",
- "setup.cfg",
- "testing/.gitignore",
- "tests/unit/gapic/talent_v4/__init__.py",
- "tests/unit/gapic/talent_v4/test_company_service.py",
- "tests/unit/gapic/talent_v4/test_completion.py",
- "tests/unit/gapic/talent_v4/test_event_service.py",
- "tests/unit/gapic/talent_v4/test_job_service.py",
- "tests/unit/gapic/talent_v4/test_tenant_service.py",
- "tests/unit/gapic/talent_v4beta1/__init__.py",
- "tests/unit/gapic/talent_v4beta1/test_application_service.py",
- "tests/unit/gapic/talent_v4beta1/test_company_service.py",
- "tests/unit/gapic/talent_v4beta1/test_completion.py",
- "tests/unit/gapic/talent_v4beta1/test_event_service.py",
- "tests/unit/gapic/talent_v4beta1/test_job_service.py",
- "tests/unit/gapic/talent_v4beta1/test_profile_service.py",
- "tests/unit/gapic/talent_v4beta1/test_tenant_service.py"
- ]
-}
\ No newline at end of file
diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt
index 2923be13..08426014 100644
--- a/testing/constraints-3.6.txt
+++ b/testing/constraints-3.6.txt
@@ -5,6 +5,6 @@
#
# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev",
# Then this file should have foo==1.14.0
-google-api-core==1.22.0
-proto-plus==1.4.0
-libcst==0.2.5
\ No newline at end of file
+google-api-core==1.26.0
+proto-plus==1.15.0
+packaging==14.3
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 00000000..4de65971
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py
new file mode 100644
index 00000000..4de65971
--- /dev/null
+++ b/tests/unit/__init__.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py
new file mode 100644
index 00000000..4de65971
--- /dev/null
+++ b/tests/unit/gapic/__init__.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/tests/unit/gapic/talent_v4/__init__.py b/tests/unit/gapic/talent_v4/__init__.py
index 8b137891..4de65971 100644
--- a/tests/unit/gapic/talent_v4/__init__.py
+++ b/tests/unit/gapic/talent_v4/__init__.py
@@ -1 +1,15 @@
-
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/tests/unit/gapic/talent_v4/test_company_service.py b/tests/unit/gapic/talent_v4/test_company_service.py
index bcb62811..d0c2a044 100644
--- a/tests/unit/gapic/talent_v4/test_company_service.py
+++ b/tests/unit/gapic/talent_v4/test_company_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,26 +23,44 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4.services.company_service import CompanyServiceAsyncClient
from google.cloud.talent_v4.services.company_service import CompanyServiceClient
from google.cloud.talent_v4.services.company_service import pagers
from google.cloud.talent_v4.services.company_service import transports
+from google.cloud.talent_v4.services.company_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import company
from google.cloud.talent_v4.types import company as gct_company
from google.cloud.talent_v4.types import company_service
from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import postal_address_pb2 as postal_address # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -91,26 +108,78 @@ def test__get_default_mtls_endpoint():
@pytest.mark.parametrize(
- "client_class", [CompanyServiceClient, CompanyServiceAsyncClient]
+ "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,]
+)
+def test_company_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,]
+)
+def test_company_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.CompanyServiceGrpcTransport, "grpc"),
+ (transports.CompanyServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_company_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize(
+ "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,]
)
def test_company_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_company_service_client_get_transport_class():
transport = CompanyServiceClient.get_transport_class()
- assert transport == transports.CompanyServiceGrpcTransport
+ available_transports = [
+ transports.CompanyServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = CompanyServiceClient.get_transport_class("grpc")
assert transport == transports.CompanyServiceGrpcTransport
@@ -142,7 +211,7 @@ def test_company_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(CompanyServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -161,7 +230,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -177,7 +246,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -193,7 +262,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -221,7 +290,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -272,29 +341,25 @@ def test_company_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -303,66 +368,53 @@ def test_company_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -388,7 +440,7 @@ def test_company_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -418,7 +470,7 @@ def test_company_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -437,7 +489,7 @@ def test_company_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -447,7 +499,7 @@ def test_create_company(
transport: str = "grpc", request_type=company_service.CreateCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -473,43 +525,28 @@ def test_create_company(
],
suspended=True,
)
-
response = client.create_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.CreateCompanyRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -517,12 +554,27 @@ def test_create_company_from_dict():
test_create_company(request_type=dict)
+def test_create_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_company), "__call__") as call:
+ client.create_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.CreateCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_create_company_async(
transport: str = "grpc_asyncio", request_type=company_service.CreateCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -550,42 +602,28 @@ async def test_create_company_async(
suspended=True,
)
)
-
response = await client.create_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.CreateCompanyRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -595,17 +633,17 @@ async def test_create_company_async_from_dict():
def test_create_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.CreateCompanyRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
call.return_value = gct_company.Company()
-
client.create_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -620,17 +658,19 @@ def test_create_company_field_headers():
@pytest.mark.asyncio
async def test_create_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.CreateCompanyRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_company.Company())
-
await client.create_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -644,13 +684,12 @@ async def test_create_company_field_headers_async():
def test_create_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_company.Company()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_company(
@@ -661,14 +700,12 @@ def test_create_company_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].company == gct_company.Company(name="name_value")
def test_create_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -682,7 +719,9 @@ def test_create_company_flattened_error():
@pytest.mark.asyncio
async def test_create_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
@@ -700,15 +739,15 @@ async def test_create_company_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].company == gct_company.Company(name="name_value")
@pytest.mark.asyncio
async def test_create_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -724,7 +763,7 @@ def test_get_company(
transport: str = "grpc", request_type=company_service.GetCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -750,43 +789,28 @@ def test_get_company(
],
suspended=True,
)
-
response = client.get_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.GetCompanyRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -794,12 +818,27 @@ def test_get_company_from_dict():
test_get_company(request_type=dict)
+def test_get_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_company), "__call__") as call:
+ client.get_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.GetCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_get_company_async(
transport: str = "grpc_asyncio", request_type=company_service.GetCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -827,42 +866,28 @@ async def test_get_company_async(
suspended=True,
)
)
-
response = await client.get_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.GetCompanyRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -872,17 +897,17 @@ async def test_get_company_async_from_dict():
def test_get_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.GetCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
call.return_value = company.Company()
-
client.get_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -897,17 +922,19 @@ def test_get_company_field_headers():
@pytest.mark.asyncio
async def test_get_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.GetCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(company.Company())
-
await client.get_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -921,13 +948,12 @@ async def test_get_company_field_headers_async():
def test_get_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = company.Company()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_company(name="name_value",)
@@ -936,12 +962,11 @@ def test_get_company_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -953,7 +978,9 @@ def test_get_company_flattened_error():
@pytest.mark.asyncio
async def test_get_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
@@ -969,13 +996,14 @@ async def test_get_company_flattened_async():
# 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_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -989,7 +1017,7 @@ def test_update_company(
transport: str = "grpc", request_type=company_service.UpdateCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1015,43 +1043,28 @@ def test_update_company(
],
suspended=True,
)
-
response = client.update_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.UpdateCompanyRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -1059,12 +1072,27 @@ def test_update_company_from_dict():
test_update_company(request_type=dict)
+def test_update_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_company), "__call__") as call:
+ client.update_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.UpdateCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_update_company_async(
transport: str = "grpc_asyncio", request_type=company_service.UpdateCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1092,42 +1120,28 @@ async def test_update_company_async(
suspended=True,
)
)
-
response = await client.update_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.UpdateCompanyRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -1137,17 +1151,17 @@ async def test_update_company_async_from_dict():
def test_update_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.UpdateCompanyRequest()
+
request.company.name = "company.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
call.return_value = gct_company.Company()
-
client.update_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1164,17 +1178,19 @@ def test_update_company_field_headers():
@pytest.mark.asyncio
async def test_update_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.UpdateCompanyRequest()
+
request.company.name = "company.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_company.Company())
-
await client.update_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1190,32 +1206,29 @@ async def test_update_company_field_headers_async():
def test_update_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_company.Company()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_company(
company=gct_company.Company(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].company == gct_company.Company(name="name_value")
-
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+ assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"])
def test_update_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1223,13 +1236,15 @@ def test_update_company_flattened_error():
client.update_company(
company_service.UpdateCompanyRequest(),
company=gct_company.Company(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@pytest.mark.asyncio
async def test_update_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
@@ -1241,22 +1256,22 @@ async def test_update_company_flattened_async():
# using the keyword arguments to the method.
response = await client.update_company(
company=gct_company.Company(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].company == gct_company.Company(name="name_value")
-
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+ assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"])
@pytest.mark.asyncio
async def test_update_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1264,7 +1279,7 @@ async def test_update_company_flattened_error_async():
await client.update_company(
company_service.UpdateCompanyRequest(),
company=gct_company.Company(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@@ -1272,7 +1287,7 @@ def test_delete_company(
transport: str = "grpc", request_type=company_service.DeleteCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1283,13 +1298,11 @@ def test_delete_company(
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.DeleteCompanyRequest()
# Establish that the response is the type that we expect.
@@ -1300,12 +1313,27 @@ def test_delete_company_from_dict():
test_delete_company(request_type=dict)
+def test_delete_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
+ client.delete_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.DeleteCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_delete_company_async(
transport: str = "grpc_asyncio", request_type=company_service.DeleteCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1316,13 +1344,11 @@ async def test_delete_company_async(
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.DeleteCompanyRequest()
# Establish that the response is the type that we expect.
@@ -1335,17 +1361,17 @@ async def test_delete_company_async_from_dict():
def test_delete_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.DeleteCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
call.return_value = None
-
client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1360,17 +1386,19 @@ def test_delete_company_field_headers():
@pytest.mark.asyncio
async def test_delete_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.DeleteCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1384,13 +1412,12 @@ async def test_delete_company_field_headers_async():
def test_delete_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__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_company(name="name_value",)
@@ -1399,12 +1426,11 @@ def test_delete_company_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1416,7 +1442,9 @@ def test_delete_company_flattened_error():
@pytest.mark.asyncio
async def test_delete_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
@@ -1432,13 +1460,14 @@ async def test_delete_company_flattened_async():
# 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_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1452,7 +1481,7 @@ def test_list_companies(
transport: str = "grpc", request_type=company_service.ListCompaniesRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1465,19 +1494,15 @@ def test_list_companies(
call.return_value = company_service.ListCompaniesResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.ListCompaniesRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListCompaniesPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1485,12 +1510,27 @@ def test_list_companies_from_dict():
test_list_companies(request_type=dict)
+def test_list_companies_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
+ client.list_companies()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.ListCompaniesRequest()
+
+
@pytest.mark.asyncio
async def test_list_companies_async(
transport: str = "grpc_asyncio", request_type=company_service.ListCompaniesRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1505,18 +1545,15 @@ async def test_list_companies_async(
next_page_token="next_page_token_value",
)
)
-
response = await client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.ListCompaniesRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListCompaniesAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1526,17 +1563,17 @@ async def test_list_companies_async_from_dict():
def test_list_companies_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.ListCompaniesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
call.return_value = company_service.ListCompaniesResponse()
-
client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
@@ -1551,11 +1588,14 @@ def test_list_companies_field_headers():
@pytest.mark.asyncio
async def test_list_companies_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.ListCompaniesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1563,7 +1603,6 @@ async def test_list_companies_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
company_service.ListCompaniesResponse()
)
-
await client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
@@ -1577,13 +1616,12 @@ async def test_list_companies_field_headers_async():
def test_list_companies_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = company_service.ListCompaniesResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_companies(parent="parent_value",)
@@ -1592,12 +1630,11 @@ def test_list_companies_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
def test_list_companies_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1609,7 +1646,9 @@ def test_list_companies_flattened_error():
@pytest.mark.asyncio
async def test_list_companies_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
@@ -1627,13 +1666,14 @@ async def test_list_companies_flattened_async():
# 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_companies_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1644,7 +1684,7 @@ async def test_list_companies_flattened_error_async():
def test_list_companies_pager():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
@@ -1678,7 +1718,7 @@ def test_list_companies_pager():
def test_list_companies_pages():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
@@ -1704,7 +1744,7 @@ def test_list_companies_pages():
@pytest.mark.asyncio
async def test_list_companies_async_pager():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1737,7 +1777,7 @@ async def test_list_companies_async_pager():
@pytest.mark.asyncio
async def test_list_companies_async_pages():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1768,16 +1808,16 @@ async def test_list_companies_async_pages():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompanyServiceClient(
@@ -1787,7 +1827,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompanyServiceClient(
@@ -1798,7 +1838,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = CompanyServiceClient(transport=transport)
assert client.transport is transport
@@ -1807,13 +1847,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.CompanyServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -1828,23 +1868,23 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.CompanyServiceGrpcTransport,)
def test_company_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.CompanyServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -1856,7 +1896,7 @@ def test_company_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.CompanyServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -1873,15 +1913,40 @@ def test_company_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_company_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4.services.company_service.transports.CompanyServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.CompanyServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_company_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4.services.company_service.transports.CompanyServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompanyServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -1897,19 +1962,36 @@ def test_company_service_base_transport_with_credentials_file():
def test_company_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4.services.company_service.transports.CompanyServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompanyServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_company_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ CompanyServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_company_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
CompanyServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -1920,14 +2002,44 @@ def test_company_service_auth_adc():
)
-def test_company_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CompanyServiceGrpcTransport,
+ transports.CompanyServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_company_service_transport_auth_adc(transport_class):
# 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.CompanyServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CompanyServiceGrpcTransport,
+ transports.CompanyServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_company_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -1937,9 +2049,92 @@ def test_company_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.CompanyServiceGrpcTransport, grpc_helpers),
+ (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_company_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CompanyServiceGrpcTransport,
+ transports.CompanyServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_company_service_host_no_port():
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -1947,7 +2142,7 @@ def test_company_service_host_no_port():
def test_company_service_host_with_port():
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -1956,7 +2151,7 @@ def test_company_service_host_with_port():
def test_company_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompanyServiceGrpcTransport(
@@ -1968,7 +2163,7 @@ def test_company_service_grpc_transport_channel():
def test_company_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompanyServiceGrpcAsyncIOTransport(
@@ -1979,6 +2174,8 @@ def test_company_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -1993,7 +2190,7 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -2001,9 +2198,9 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -2019,10 +2216,7 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2034,6 +2228,8 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -2049,7 +2245,7 @@ def test_company_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -2067,10 +2263,7 @@ def test_company_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2085,7 +2278,6 @@ def test_company_path():
project = "squid"
tenant = "clam"
company = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -2109,7 +2301,6 @@ def test_parse_company_path():
def test_tenant_path():
project = "cuttlefish"
tenant = "mussel"
-
expected = "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@@ -2131,7 +2322,6 @@ def test_parse_tenant_path():
def test_common_billing_account_path():
billing_account = "scallop"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -2152,7 +2342,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "squid"
-
expected = "folders/{folder}".format(folder=folder,)
actual = CompanyServiceClient.common_folder_path(folder)
assert expected == actual
@@ -2171,7 +2360,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "whelk"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = CompanyServiceClient.common_organization_path(organization)
assert expected == actual
@@ -2190,7 +2378,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "oyster"
-
expected = "projects/{project}".format(project=project,)
actual = CompanyServiceClient.common_project_path(project)
assert expected == actual
@@ -2210,7 +2397,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "cuttlefish"
location = "mussel"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -2237,7 +2423,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.CompanyServiceTransport, "_prep_wrapped_messages"
) as prep:
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -2246,6 +2432,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = CompanyServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4/test_completion.py b/tests/unit/gapic/talent_v4/test_completion.py
index cafd4bc5..051e8fdd 100644
--- a/tests/unit/gapic/talent_v4/test_completion.py
+++ b/tests/unit/gapic/talent_v4/test_completion.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,20 +23,38 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4.services.completion import CompletionAsyncClient
from google.cloud.talent_v4.services.completion import CompletionClient
from google.cloud.talent_v4.services.completion import transports
+from google.cloud.talent_v4.services.completion.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import completion_service
from google.oauth2 import service_account
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -81,25 +98,73 @@ def test__get_default_mtls_endpoint():
assert CompletionClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
-@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient])
+@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,])
+def test_completion_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,])
+def test_completion_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.CompletionGrpcTransport, "grpc"),
+ (transports.CompletionGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_completion_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,])
def test_completion_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_completion_client_get_transport_class():
transport = CompletionClient.get_transport_class()
- assert transport == transports.CompletionGrpcTransport
+ available_transports = [
+ transports.CompletionGrpcTransport,
+ ]
+ assert transport in available_transports
transport = CompletionClient.get_transport_class("grpc")
assert transport == transports.CompletionGrpcTransport
@@ -129,7 +194,7 @@ def test_completion_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(CompletionClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -148,7 +213,7 @@ def test_completion_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -164,7 +229,7 @@ def test_completion_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -180,7 +245,7 @@ def test_completion_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -208,7 +273,7 @@ def test_completion_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -257,29 +322,25 @@ def test_completion_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -288,66 +349,53 @@ def test_completion_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -373,7 +421,7 @@ def test_completion_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -403,7 +451,7 @@ def test_completion_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -420,7 +468,7 @@ def test_completion_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -430,7 +478,7 @@ def test_complete_query(
transport: str = "grpc", request_type=completion_service.CompleteQueryRequest
):
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -441,17 +489,14 @@ def test_complete_query(
with mock.patch.object(type(client.transport.complete_query), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = completion_service.CompleteQueryResponse()
-
response = client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == completion_service.CompleteQueryRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, completion_service.CompleteQueryResponse)
@@ -459,13 +504,28 @@ def test_complete_query_from_dict():
test_complete_query(request_type=dict)
+def test_complete_query_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompletionClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.complete_query), "__call__") as call:
+ client.complete_query()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == completion_service.CompleteQueryRequest()
+
+
@pytest.mark.asyncio
async def test_complete_query_async(
transport: str = "grpc_asyncio",
request_type=completion_service.CompleteQueryRequest,
):
client = CompletionAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -478,13 +538,11 @@ async def test_complete_query_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
completion_service.CompleteQueryResponse()
)
-
response = await client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == completion_service.CompleteQueryRequest()
# Establish that the response is the type that we expect.
@@ -497,17 +555,17 @@ async def test_complete_query_async_from_dict():
def test_complete_query_field_headers():
- client = CompletionClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompletionClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = completion_service.CompleteQueryRequest()
+
request.tenant = "tenant/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.complete_query), "__call__") as call:
call.return_value = completion_service.CompleteQueryResponse()
-
client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
@@ -522,11 +580,12 @@ def test_complete_query_field_headers():
@pytest.mark.asyncio
async def test_complete_query_field_headers_async():
- client = CompletionAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompletionAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = completion_service.CompleteQueryRequest()
+
request.tenant = "tenant/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -534,7 +593,6 @@ async def test_complete_query_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
completion_service.CompleteQueryResponse()
)
-
await client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
@@ -550,16 +608,16 @@ async def test_complete_query_field_headers_async():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompletionClient(
@@ -569,7 +627,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompletionClient(
@@ -580,7 +638,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = CompletionClient(transport=transport)
assert client.transport is transport
@@ -589,13 +647,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.CompletionGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -603,27 +661,27 @@ def test_transport_get_channel():
@pytest.mark.parametrize(
"transport_class",
- [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport,],
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = CompletionClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompletionClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.CompletionGrpcTransport,)
def test_completion_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.CompletionTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -635,7 +693,7 @@ def test_completion_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.CompletionTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -646,15 +704,40 @@ def test_completion_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_completion_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4.services.completion.transports.CompletionTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.CompletionTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_completion_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4.services.completion.transports.CompletionTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompletionTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -670,19 +753,36 @@ def test_completion_base_transport_with_credentials_file():
def test_completion_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4.services.completion.transports.CompletionTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompletionTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_completion_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ CompletionClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_completion_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
CompletionClient()
adc.assert_called_once_with(
scopes=(
@@ -693,14 +793,38 @@ def test_completion_auth_adc():
)
-def test_completion_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport,],
+)
+@requires_google_auth_gte_1_25_0
+def test_completion_transport_auth_adc(transport_class):
# 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.CompletionGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport,],
+)
+@requires_google_auth_lt_1_25_0
+def test_completion_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -710,9 +834,89 @@ def test_completion_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.CompletionGrpcTransport, grpc_helpers),
+ (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_completion_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
+)
+def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_completion_host_no_port():
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -720,7 +924,7 @@ def test_completion_host_no_port():
def test_completion_host_with_port():
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -729,7 +933,7 @@ def test_completion_host_with_port():
def test_completion_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompletionGrpcTransport(
@@ -741,7 +945,7 @@ def test_completion_grpc_transport_channel():
def test_completion_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompletionGrpcAsyncIOTransport(
@@ -752,6 +956,8 @@ def test_completion_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
@@ -761,7 +967,7 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -769,9 +975,9 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -787,10 +993,7 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -802,6 +1005,8 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
@@ -814,7 +1019,7 @@ def test_completion_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -832,10 +1037,7 @@ def test_completion_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -850,7 +1052,6 @@ def test_company_path():
project = "squid"
tenant = "clam"
company = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -874,7 +1075,6 @@ def test_parse_company_path():
def test_tenant_path():
project = "cuttlefish"
tenant = "mussel"
-
expected = "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@@ -896,7 +1096,6 @@ def test_parse_tenant_path():
def test_common_billing_account_path():
billing_account = "scallop"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -917,7 +1116,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "squid"
-
expected = "folders/{folder}".format(folder=folder,)
actual = CompletionClient.common_folder_path(folder)
assert expected == actual
@@ -936,7 +1134,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "whelk"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = CompletionClient.common_organization_path(organization)
assert expected == actual
@@ -955,7 +1152,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "oyster"
-
expected = "projects/{project}".format(project=project,)
actual = CompletionClient.common_project_path(project)
assert expected == actual
@@ -975,7 +1171,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "cuttlefish"
location = "mussel"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -1002,7 +1197,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.CompletionTransport, "_prep_wrapped_messages"
) as prep:
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -1011,6 +1206,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = CompletionClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4/test_event_service.py b/tests/unit/gapic/talent_v4/test_event_service.py
index dcf80843..434d3aa4 100644
--- a/tests/unit/gapic/talent_v4/test_event_service.py
+++ b/tests/unit/gapic/talent_v4/test_event_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,21 +23,39 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4.services.event_service import EventServiceAsyncClient
from google.cloud.talent_v4.services.event_service import EventServiceClient
from google.cloud.talent_v4.services.event_service import transports
+from google.cloud.talent_v4.services.event_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4.types import event
from google.cloud.talent_v4.types import event_service
from google.oauth2 import service_account
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -82,25 +99,73 @@ def test__get_default_mtls_endpoint():
assert EventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
-@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient])
+@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,])
+def test_event_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,])
+def test_event_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.EventServiceGrpcTransport, "grpc"),
+ (transports.EventServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_event_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,])
def test_event_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_event_service_client_get_transport_class():
transport = EventServiceClient.get_transport_class()
- assert transport == transports.EventServiceGrpcTransport
+ available_transports = [
+ transports.EventServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = EventServiceClient.get_transport_class("grpc")
assert transport == transports.EventServiceGrpcTransport
@@ -130,7 +195,7 @@ def test_event_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(EventServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -149,7 +214,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -165,7 +230,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -181,7 +246,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -209,7 +274,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -258,29 +323,25 @@ def test_event_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -289,66 +350,53 @@ def test_event_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -374,7 +422,7 @@ def test_event_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -404,7 +452,7 @@ def test_event_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -421,7 +469,7 @@ def test_event_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -431,7 +479,7 @@ def test_create_client_event(
transport: str = "grpc", request_type=event_service.CreateClientEventRequest
):
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -449,23 +497,17 @@ def test_create_client_event(
event_notes="event_notes_value",
job_event=event.JobEvent(type_=event.JobEvent.JobEventType.IMPRESSION),
)
-
response = client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == event_service.CreateClientEventRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, event.ClientEvent)
-
assert response.request_id == "request_id_value"
-
assert response.event_id == "event_id_value"
-
assert response.event_notes == "event_notes_value"
@@ -473,12 +515,29 @@ def test_create_client_event_from_dict():
test_create_client_event(request_type=dict)
+def test_create_client_event_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EventServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_client_event), "__call__"
+ ) as call:
+ client.create_client_event()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == event_service.CreateClientEventRequest()
+
+
@pytest.mark.asyncio
async def test_create_client_event_async(
transport: str = "grpc_asyncio", request_type=event_service.CreateClientEventRequest
):
client = EventServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -497,22 +556,17 @@ async def test_create_client_event_async(
event_notes="event_notes_value",
)
)
-
response = await client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == event_service.CreateClientEventRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, event.ClientEvent)
-
assert response.request_id == "request_id_value"
-
assert response.event_id == "event_id_value"
-
assert response.event_notes == "event_notes_value"
@@ -522,11 +576,12 @@ async def test_create_client_event_async_from_dict():
def test_create_client_event_field_headers():
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = event_service.CreateClientEventRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -534,7 +589,6 @@ def test_create_client_event_field_headers():
type(client.transport.create_client_event), "__call__"
) as call:
call.return_value = event.ClientEvent()
-
client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
@@ -549,11 +603,12 @@ def test_create_client_event_field_headers():
@pytest.mark.asyncio
async def test_create_client_event_field_headers_async():
- client = EventServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = event_service.CreateClientEventRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -561,7 +616,6 @@ async def test_create_client_event_field_headers_async():
type(client.transport.create_client_event), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event.ClientEvent())
-
await client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
@@ -575,7 +629,7 @@ async def test_create_client_event_field_headers_async():
def test_create_client_event_flattened():
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -583,7 +637,6 @@ def test_create_client_event_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = event.ClientEvent()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_client_event(
@@ -595,14 +648,12 @@ def test_create_client_event_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].client_event == event.ClientEvent(request_id="request_id_value")
def test_create_client_event_flattened_error():
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -616,7 +667,7 @@ def test_create_client_event_flattened_error():
@pytest.mark.asyncio
async def test_create_client_event_flattened_async():
- client = EventServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -637,15 +688,13 @@ async def test_create_client_event_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].client_event == event.ClientEvent(request_id="request_id_value")
@pytest.mark.asyncio
async def test_create_client_event_flattened_error_async():
- client = EventServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -660,16 +709,16 @@ async def test_create_client_event_flattened_error_async():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = EventServiceClient(
@@ -679,7 +728,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = EventServiceClient(
@@ -690,7 +739,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = EventServiceClient(transport=transport)
assert client.transport is transport
@@ -699,13 +748,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.EventServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -713,27 +762,30 @@ def test_transport_get_channel():
@pytest.mark.parametrize(
"transport_class",
- [transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
+ [
+ transports.EventServiceGrpcTransport,
+ transports.EventServiceGrpcAsyncIOTransport,
+ ],
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.EventServiceGrpcTransport,)
def test_event_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.EventServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -745,7 +797,7 @@ def test_event_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.EventServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -756,15 +808,40 @@ def test_event_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_event_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4.services.event_service.transports.EventServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.EventServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_event_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4.services.event_service.transports.EventServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.EventServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -780,19 +857,36 @@ def test_event_service_base_transport_with_credentials_file():
def test_event_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4.services.event_service.transports.EventServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.EventServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_event_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ EventServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_event_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
EventServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -803,14 +897,44 @@ def test_event_service_auth_adc():
)
-def test_event_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.EventServiceGrpcTransport,
+ transports.EventServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_event_service_transport_auth_adc(transport_class):
# 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.EventServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.EventServiceGrpcTransport,
+ transports.EventServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_event_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -820,9 +944,89 @@ def test_event_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.EventServiceGrpcTransport, grpc_helpers),
+ (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_event_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
+)
+def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_event_service_host_no_port():
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -830,7 +1034,7 @@ def test_event_service_host_no_port():
def test_event_service_host_with_port():
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -839,7 +1043,7 @@ def test_event_service_host_with_port():
def test_event_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.EventServiceGrpcTransport(
@@ -851,7 +1055,7 @@ def test_event_service_grpc_transport_channel():
def test_event_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.EventServiceGrpcAsyncIOTransport(
@@ -862,6 +1066,8 @@ def test_event_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
@@ -871,7 +1077,7 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -879,9 +1085,9 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -897,10 +1103,7 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -912,6 +1115,8 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
@@ -924,7 +1129,7 @@ def test_event_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -942,10 +1147,7 @@ def test_event_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -959,7 +1161,6 @@ def test_event_service_transport_channel_mtls_with_adc(transport_class):
def test_tenant_path():
project = "squid"
tenant = "clam"
-
expected = "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@@ -981,7 +1182,6 @@ def test_parse_tenant_path():
def test_common_billing_account_path():
billing_account = "oyster"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -1002,7 +1202,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "cuttlefish"
-
expected = "folders/{folder}".format(folder=folder,)
actual = EventServiceClient.common_folder_path(folder)
assert expected == actual
@@ -1021,7 +1220,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "winkle"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = EventServiceClient.common_organization_path(organization)
assert expected == actual
@@ -1040,7 +1238,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "scallop"
-
expected = "projects/{project}".format(project=project,)
actual = EventServiceClient.common_project_path(project)
assert expected == actual
@@ -1060,7 +1257,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "squid"
location = "clam"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -1087,7 +1283,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.EventServiceTransport, "_prep_wrapped_messages"
) as prep:
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -1096,6 +1292,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = EventServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4/test_job_service.py b/tests/unit/gapic/talent_v4/test_job_service.py
index 208347d4..b488f41a 100644
--- a/tests/unit/gapic/talent_v4/test_job_service.py
+++ b/tests/unit/gapic/talent_v4/test_job_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,21 +23,24 @@
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 exceptions as core_exceptions
from google.api_core import future
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import operation_async # type: ignore
from google.api_core import operations_v1
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4.services.job_service import JobServiceAsyncClient
from google.cloud.talent_v4.services.job_service import JobServiceClient
from google.cloud.talent_v4.services.job_service import pagers
from google.cloud.talent_v4.services.job_service import transports
+from google.cloud.talent_v4.services.job_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4.types import common
from google.cloud.talent_v4.types import filters
from google.cloud.talent_v4.types import histogram
@@ -47,14 +49,29 @@
from google.cloud.talent_v4.types import job_service
from google.longrunning import operations_pb2
from google.oauth2 import service_account
-from google.protobuf import duration_pb2 as duration # type: ignore
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import money_pb2 as money # type: ignore
-from google.type import postal_address_pb2 as postal_address # type: ignore
-from google.type import timeofday_pb2 as timeofday # type: ignore
+from google.protobuf import duration_pb2 # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import money_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
+from google.type import timeofday_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -98,25 +115,73 @@ def test__get_default_mtls_endpoint():
assert JobServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
-@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient])
+@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,])
+def test_job_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,])
+def test_job_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.JobServiceGrpcTransport, "grpc"),
+ (transports.JobServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_job_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,])
def test_job_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_job_service_client_get_transport_class():
transport = JobServiceClient.get_transport_class()
- assert transport == transports.JobServiceGrpcTransport
+ available_transports = [
+ transports.JobServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = JobServiceClient.get_transport_class("grpc")
assert transport == transports.JobServiceGrpcTransport
@@ -146,7 +211,7 @@ def test_job_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(JobServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -165,7 +230,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -181,7 +246,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -197,7 +262,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -225,7 +290,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -274,29 +339,25 @@ def test_job_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -305,66 +366,53 @@ def test_job_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -390,7 +438,7 @@ def test_job_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -420,7 +468,7 @@ def test_job_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -437,7 +485,7 @@ def test_job_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -445,7 +493,7 @@ def test_job_service_client_client_options_from_dict():
def test_create_job(transport: str = "grpc", request_type=job_service.CreateJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -476,55 +524,33 @@ def test_create_job(transport: str = "grpc", request_type=job_service.CreateJobR
visibility=common.Visibility.ACCOUNT_ONLY,
company_display_name="company_display_name_value",
)
-
response = client.create_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.CreateJobRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -532,12 +558,27 @@ def test_create_job_from_dict():
test_create_job(request_type=dict)
+def test_create_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_job), "__call__") as call:
+ client.create_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.CreateJobRequest()
+
+
@pytest.mark.asyncio
async def test_create_job_async(
transport: str = "grpc_asyncio", request_type=job_service.CreateJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -570,54 +611,33 @@ async def test_create_job_async(
company_display_name="company_display_name_value",
)
)
-
response = await client.create_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.CreateJobRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -627,17 +647,17 @@ async def test_create_job_async_from_dict():
def test_create_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.CreateJobRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
call.return_value = gct_job.Job()
-
client.create_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -652,17 +672,17 @@ def test_create_job_field_headers():
@pytest.mark.asyncio
async def test_create_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.CreateJobRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_job.Job())
-
await client.create_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -676,13 +696,12 @@ async def test_create_job_field_headers_async():
def test_create_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_job.Job()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_job(
@@ -693,14 +712,12 @@ def test_create_job_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].job == gct_job.Job(name="name_value")
def test_create_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -714,7 +731,7 @@ def test_create_job_flattened_error():
@pytest.mark.asyncio
async def test_create_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
@@ -732,15 +749,13 @@ async def test_create_job_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].job == gct_job.Job(name="name_value")
@pytest.mark.asyncio
async def test_create_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -756,7 +771,7 @@ def test_batch_create_jobs(
transport: str = "grpc", request_type=job_service.BatchCreateJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -769,13 +784,11 @@ def test_batch_create_jobs(
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/spam")
-
response = client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchCreateJobsRequest()
# Establish that the response is the type that we expect.
@@ -786,12 +799,29 @@ def test_batch_create_jobs_from_dict():
test_batch_create_jobs(request_type=dict)
+def test_batch_create_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_create_jobs), "__call__"
+ ) as call:
+ client.batch_create_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.BatchCreateJobsRequest()
+
+
@pytest.mark.asyncio
async def test_batch_create_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.BatchCreateJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -806,13 +836,11 @@ async def test_batch_create_jobs_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/spam")
)
-
response = await client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchCreateJobsRequest()
# Establish that the response is the type that we expect.
@@ -825,11 +853,12 @@ async def test_batch_create_jobs_async_from_dict():
def test_batch_create_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchCreateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -837,7 +866,6 @@ def test_batch_create_jobs_field_headers():
type(client.transport.batch_create_jobs), "__call__"
) as call:
call.return_value = operations_pb2.Operation(name="operations/op")
-
client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -852,11 +880,12 @@ def test_batch_create_jobs_field_headers():
@pytest.mark.asyncio
async def test_batch_create_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchCreateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -866,7 +895,6 @@ async def test_batch_create_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/op")
)
-
await client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -880,7 +908,7 @@ async def test_batch_create_jobs_field_headers_async():
def test_batch_create_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -888,7 +916,6 @@ def test_batch_create_jobs_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/op")
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.batch_create_jobs(
@@ -899,14 +926,12 @@ def test_batch_create_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
def test_batch_create_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -920,7 +945,7 @@ def test_batch_create_jobs_flattened_error():
@pytest.mark.asyncio
async def test_batch_create_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -942,15 +967,13 @@ async def test_batch_create_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
@pytest.mark.asyncio
async def test_batch_create_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -964,7 +987,7 @@ async def test_batch_create_jobs_flattened_error_async():
def test_get_job(transport: str = "grpc", request_type=job_service.GetJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -995,55 +1018,33 @@ def test_get_job(transport: str = "grpc", request_type=job_service.GetJobRequest
visibility=common.Visibility.ACCOUNT_ONLY,
company_display_name="company_display_name_value",
)
-
response = client.get_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.GetJobRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1051,12 +1052,27 @@ def test_get_job_from_dict():
test_get_job(request_type=dict)
+def test_get_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_job), "__call__") as call:
+ client.get_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.GetJobRequest()
+
+
@pytest.mark.asyncio
async def test_get_job_async(
transport: str = "grpc_asyncio", request_type=job_service.GetJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1089,54 +1105,33 @@ async def test_get_job_async(
company_display_name="company_display_name_value",
)
)
-
response = await client.get_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.GetJobRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1146,17 +1141,17 @@ async def test_get_job_async_from_dict():
def test_get_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.GetJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
call.return_value = job.Job()
-
client.get_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1171,17 +1166,17 @@ def test_get_job_field_headers():
@pytest.mark.asyncio
async def test_get_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.GetJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job())
-
await client.get_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1195,13 +1190,12 @@ async def test_get_job_field_headers_async():
def test_get_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = job.Job()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_job(name="name_value",)
@@ -1210,12 +1204,11 @@ def test_get_job_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1227,7 +1220,7 @@ def test_get_job_flattened_error():
@pytest.mark.asyncio
async def test_get_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
@@ -1243,13 +1236,12 @@ async def test_get_job_flattened_async():
# 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_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1261,7 +1253,7 @@ async def test_get_job_flattened_error_async():
def test_update_job(transport: str = "grpc", request_type=job_service.UpdateJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1292,55 +1284,33 @@ def test_update_job(transport: str = "grpc", request_type=job_service.UpdateJobR
visibility=common.Visibility.ACCOUNT_ONLY,
company_display_name="company_display_name_value",
)
-
response = client.update_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.UpdateJobRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1348,12 +1318,27 @@ def test_update_job_from_dict():
test_update_job(request_type=dict)
+def test_update_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_job), "__call__") as call:
+ client.update_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.UpdateJobRequest()
+
+
@pytest.mark.asyncio
async def test_update_job_async(
transport: str = "grpc_asyncio", request_type=job_service.UpdateJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1386,54 +1371,33 @@ async def test_update_job_async(
company_display_name="company_display_name_value",
)
)
-
response = await client.update_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.UpdateJobRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1443,17 +1407,17 @@ async def test_update_job_async_from_dict():
def test_update_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.UpdateJobRequest()
+
request.job.name = "job.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
call.return_value = gct_job.Job()
-
client.update_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1468,17 +1432,17 @@ def test_update_job_field_headers():
@pytest.mark.asyncio
async def test_update_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.UpdateJobRequest()
+
request.job.name = "job.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_job.Job())
-
await client.update_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1492,32 +1456,29 @@ async def test_update_job_field_headers_async():
def test_update_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_job.Job()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_job(
job=gct_job.Job(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].job == gct_job.Job(name="name_value")
-
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+ assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"])
def test_update_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1525,13 +1486,13 @@ def test_update_job_flattened_error():
client.update_job(
job_service.UpdateJobRequest(),
job=gct_job.Job(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@pytest.mark.asyncio
async def test_update_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
@@ -1543,22 +1504,20 @@ async def test_update_job_flattened_async():
# using the keyword arguments to the method.
response = await client.update_job(
job=gct_job.Job(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].job == gct_job.Job(name="name_value")
-
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+ assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"])
@pytest.mark.asyncio
async def test_update_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1566,7 +1525,7 @@ async def test_update_job_flattened_error_async():
await client.update_job(
job_service.UpdateJobRequest(),
job=gct_job.Job(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@@ -1574,7 +1533,7 @@ def test_batch_update_jobs(
transport: str = "grpc", request_type=job_service.BatchUpdateJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1587,13 +1546,11 @@ def test_batch_update_jobs(
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/spam")
-
response = client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchUpdateJobsRequest()
# Establish that the response is the type that we expect.
@@ -1604,12 +1561,29 @@ def test_batch_update_jobs_from_dict():
test_batch_update_jobs(request_type=dict)
+def test_batch_update_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_jobs), "__call__"
+ ) as call:
+ client.batch_update_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.BatchUpdateJobsRequest()
+
+
@pytest.mark.asyncio
async def test_batch_update_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.BatchUpdateJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1624,13 +1598,11 @@ async def test_batch_update_jobs_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/spam")
)
-
response = await client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchUpdateJobsRequest()
# Establish that the response is the type that we expect.
@@ -1643,11 +1615,12 @@ async def test_batch_update_jobs_async_from_dict():
def test_batch_update_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchUpdateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1655,7 +1628,6 @@ def test_batch_update_jobs_field_headers():
type(client.transport.batch_update_jobs), "__call__"
) as call:
call.return_value = operations_pb2.Operation(name="operations/op")
-
client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -1670,11 +1642,12 @@ def test_batch_update_jobs_field_headers():
@pytest.mark.asyncio
async def test_batch_update_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchUpdateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1684,7 +1657,6 @@ async def test_batch_update_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/op")
)
-
await client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -1698,7 +1670,7 @@ async def test_batch_update_jobs_field_headers_async():
def test_batch_update_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1706,7 +1678,6 @@ def test_batch_update_jobs_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/op")
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.batch_update_jobs(
@@ -1717,14 +1688,12 @@ def test_batch_update_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
def test_batch_update_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1738,7 +1707,7 @@ def test_batch_update_jobs_flattened_error():
@pytest.mark.asyncio
async def test_batch_update_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1760,15 +1729,13 @@ async def test_batch_update_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
@pytest.mark.asyncio
async def test_batch_update_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1782,7 +1749,7 @@ async def test_batch_update_jobs_flattened_error_async():
def test_delete_job(transport: str = "grpc", request_type=job_service.DeleteJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1793,13 +1760,11 @@ def test_delete_job(transport: str = "grpc", request_type=job_service.DeleteJobR
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.DeleteJobRequest()
# Establish that the response is the type that we expect.
@@ -1810,12 +1775,27 @@ def test_delete_job_from_dict():
test_delete_job(request_type=dict)
+def test_delete_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
+ client.delete_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.DeleteJobRequest()
+
+
@pytest.mark.asyncio
async def test_delete_job_async(
transport: str = "grpc_asyncio", request_type=job_service.DeleteJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1826,13 +1806,11 @@ async def test_delete_job_async(
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.DeleteJobRequest()
# Establish that the response is the type that we expect.
@@ -1845,17 +1823,17 @@ async def test_delete_job_async_from_dict():
def test_delete_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.DeleteJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
call.return_value = None
-
client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1870,17 +1848,17 @@ def test_delete_job_field_headers():
@pytest.mark.asyncio
async def test_delete_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.DeleteJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1894,13 +1872,12 @@ async def test_delete_job_field_headers_async():
def test_delete_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__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_job(name="name_value",)
@@ -1909,12 +1886,11 @@ def test_delete_job_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1926,7 +1902,7 @@ def test_delete_job_flattened_error():
@pytest.mark.asyncio
async def test_delete_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
@@ -1942,13 +1918,12 @@ async def test_delete_job_flattened_async():
# 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_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1962,7 +1937,7 @@ def test_batch_delete_jobs(
transport: str = "grpc", request_type=job_service.BatchDeleteJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1975,13 +1950,11 @@ def test_batch_delete_jobs(
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/spam")
-
response = client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchDeleteJobsRequest()
# Establish that the response is the type that we expect.
@@ -1992,12 +1965,29 @@ def test_batch_delete_jobs_from_dict():
test_batch_delete_jobs(request_type=dict)
+def test_batch_delete_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_delete_jobs), "__call__"
+ ) as call:
+ client.batch_delete_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.BatchDeleteJobsRequest()
+
+
@pytest.mark.asyncio
async def test_batch_delete_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.BatchDeleteJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2012,13 +2002,11 @@ async def test_batch_delete_jobs_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/spam")
)
-
response = await client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchDeleteJobsRequest()
# Establish that the response is the type that we expect.
@@ -2031,11 +2019,12 @@ async def test_batch_delete_jobs_async_from_dict():
def test_batch_delete_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchDeleteJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2043,7 +2032,6 @@ def test_batch_delete_jobs_field_headers():
type(client.transport.batch_delete_jobs), "__call__"
) as call:
call.return_value = operations_pb2.Operation(name="operations/op")
-
client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2058,11 +2046,12 @@ def test_batch_delete_jobs_field_headers():
@pytest.mark.asyncio
async def test_batch_delete_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchDeleteJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2072,7 +2061,6 @@ async def test_batch_delete_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/op")
)
-
await client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2086,7 +2074,7 @@ async def test_batch_delete_jobs_field_headers_async():
def test_batch_delete_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2094,7 +2082,6 @@ def test_batch_delete_jobs_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/op")
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.batch_delete_jobs(
@@ -2105,14 +2092,12 @@ def test_batch_delete_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].names == ["names_value"]
def test_batch_delete_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2126,7 +2111,7 @@ def test_batch_delete_jobs_flattened_error():
@pytest.mark.asyncio
async def test_batch_delete_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2148,15 +2133,13 @@ async def test_batch_delete_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].names == ["names_value"]
@pytest.mark.asyncio
async def test_batch_delete_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2170,7 +2153,7 @@ async def test_batch_delete_jobs_flattened_error_async():
def test_list_jobs(transport: str = "grpc", request_type=job_service.ListJobsRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2183,19 +2166,15 @@ def test_list_jobs(transport: str = "grpc", request_type=job_service.ListJobsReq
call.return_value = job_service.ListJobsResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.ListJobsRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListJobsPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -2203,12 +2182,27 @@ def test_list_jobs_from_dict():
test_list_jobs(request_type=dict)
+def test_list_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
+ client.list_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.ListJobsRequest()
+
+
@pytest.mark.asyncio
async def test_list_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.ListJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2221,18 +2215,15 @@ async def test_list_jobs_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.ListJobsResponse(next_page_token="next_page_token_value",)
)
-
response = await client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.ListJobsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListJobsAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -2242,17 +2233,17 @@ async def test_list_jobs_async_from_dict():
def test_list_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.ListJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
call.return_value = job_service.ListJobsResponse()
-
client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2267,11 +2258,12 @@ def test_list_jobs_field_headers():
@pytest.mark.asyncio
async def test_list_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.ListJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2279,7 +2271,6 @@ async def test_list_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.ListJobsResponse()
)
-
await client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2293,13 +2284,12 @@ async def test_list_jobs_field_headers_async():
def test_list_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = job_service.ListJobsResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_jobs(
@@ -2310,14 +2300,12 @@ def test_list_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].filter == "filter_value"
def test_list_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2329,7 +2317,7 @@ def test_list_jobs_flattened_error():
@pytest.mark.asyncio
async def test_list_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
@@ -2347,15 +2335,13 @@ async def test_list_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].filter == "filter_value"
@pytest.mark.asyncio
async def test_list_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2366,7 +2352,7 @@ async def test_list_jobs_flattened_error_async():
def test_list_jobs_pager():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
@@ -2395,7 +2381,7 @@ def test_list_jobs_pager():
def test_list_jobs_pages():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
@@ -2416,7 +2402,7 @@ def test_list_jobs_pages():
@pytest.mark.asyncio
async def test_list_jobs_async_pager():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2444,7 +2430,7 @@ async def test_list_jobs_async_pager():
@pytest.mark.asyncio
async def test_list_jobs_async_pages():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2471,7 +2457,7 @@ def test_search_jobs(
transport: str = "grpc", request_type=job_service.SearchJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2486,25 +2472,18 @@ def test_search_jobs(
total_size=1086,
broadened_query_jobs_count=2766,
)
-
response = client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
-
assert response.raw_page is response
-
assert isinstance(response, job_service.SearchJobsResponse)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2512,12 +2491,27 @@ def test_search_jobs_from_dict():
test_search_jobs(request_type=dict)
+def test_search_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.search_jobs), "__call__") as call:
+ client.search_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.SearchJobsRequest()
+
+
@pytest.mark.asyncio
async def test_search_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.SearchJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2534,22 +2528,17 @@ async def test_search_jobs_async(
broadened_query_jobs_count=2766,
)
)
-
response = await client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, job_service.SearchJobsResponse)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2559,17 +2548,17 @@ async def test_search_jobs_async_from_dict():
def test_search_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.search_jobs), "__call__") as call:
call.return_value = job_service.SearchJobsResponse()
-
client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2584,11 +2573,12 @@ def test_search_jobs_field_headers():
@pytest.mark.asyncio
async def test_search_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2596,7 +2586,6 @@ async def test_search_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.SearchJobsResponse()
)
-
await client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2613,7 +2602,7 @@ def test_search_jobs_for_alert(
transport: str = "grpc", request_type=job_service.SearchJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2630,25 +2619,18 @@ def test_search_jobs_for_alert(
total_size=1086,
broadened_query_jobs_count=2766,
)
-
response = client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
-
assert response.raw_page is response
-
assert isinstance(response, job_service.SearchJobsResponse)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2656,12 +2638,29 @@ def test_search_jobs_for_alert_from_dict():
test_search_jobs_for_alert(request_type=dict)
+def test_search_jobs_for_alert_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.search_jobs_for_alert), "__call__"
+ ) as call:
+ client.search_jobs_for_alert()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.SearchJobsRequest()
+
+
@pytest.mark.asyncio
async def test_search_jobs_for_alert_async(
transport: str = "grpc_asyncio", request_type=job_service.SearchJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2680,22 +2679,17 @@ async def test_search_jobs_for_alert_async(
broadened_query_jobs_count=2766,
)
)
-
response = await client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, job_service.SearchJobsResponse)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2705,11 +2699,12 @@ async def test_search_jobs_for_alert_async_from_dict():
def test_search_jobs_for_alert_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2717,7 +2712,6 @@ def test_search_jobs_for_alert_field_headers():
type(client.transport.search_jobs_for_alert), "__call__"
) as call:
call.return_value = job_service.SearchJobsResponse()
-
client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
@@ -2732,11 +2726,12 @@ def test_search_jobs_for_alert_field_headers():
@pytest.mark.asyncio
async def test_search_jobs_for_alert_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2746,7 +2741,6 @@ async def test_search_jobs_for_alert_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.SearchJobsResponse()
)
-
await client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
@@ -2762,16 +2756,16 @@ async def test_search_jobs_for_alert_field_headers_async():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = JobServiceClient(
@@ -2781,7 +2775,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = JobServiceClient(
@@ -2792,7 +2786,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = JobServiceClient(transport=transport)
assert client.transport is transport
@@ -2801,13 +2795,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.JobServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -2815,27 +2809,27 @@ def test_transport_get_channel():
@pytest.mark.parametrize(
"transport_class",
- [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport,],
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.JobServiceGrpcTransport,)
def test_job_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.JobServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -2847,7 +2841,7 @@ def test_job_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.JobServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -2874,15 +2868,40 @@ def test_job_service_base_transport():
transport.operations_client
+@requires_google_auth_gte_1_25_0
def test_job_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4.services.job_service.transports.JobServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.JobServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_job_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4.services.job_service.transports.JobServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.JobServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -2898,19 +2917,36 @@ def test_job_service_base_transport_with_credentials_file():
def test_job_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4.services.job_service.transports.JobServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.JobServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_job_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ JobServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_job_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
JobServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -2921,14 +2957,38 @@ def test_job_service_auth_adc():
)
-def test_job_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport,],
+)
+@requires_google_auth_gte_1_25_0
+def test_job_service_transport_auth_adc(transport_class):
# 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.JobServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport,],
+)
+@requires_google_auth_lt_1_25_0
+def test_job_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -2938,9 +2998,89 @@ def test_job_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.JobServiceGrpcTransport, grpc_helpers),
+ (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_job_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
+)
+def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_job_service_host_no_port():
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -2948,7 +3088,7 @@ def test_job_service_host_no_port():
def test_job_service_host_with_port():
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -2957,7 +3097,7 @@ def test_job_service_host_with_port():
def test_job_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.JobServiceGrpcTransport(
@@ -2969,7 +3109,7 @@ def test_job_service_grpc_transport_channel():
def test_job_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.JobServiceGrpcAsyncIOTransport(
@@ -2980,6 +3120,8 @@ def test_job_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
@@ -2989,7 +3131,7 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -2997,9 +3139,9 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -3015,10 +3157,7 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -3030,6 +3169,8 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
@@ -3042,7 +3183,7 @@ def test_job_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -3060,10 +3201,7 @@ def test_job_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -3076,7 +3214,7 @@ def test_job_service_transport_channel_mtls_with_adc(transport_class):
def test_job_service_grpc_lro_client():
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc",
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
transport = client.transport
@@ -3089,7 +3227,7 @@ def test_job_service_grpc_lro_client():
def test_job_service_grpc_lro_async_client():
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
)
transport = client.transport
@@ -3104,7 +3242,6 @@ def test_company_path():
project = "squid"
tenant = "clam"
company = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -3129,7 +3266,6 @@ def test_job_path():
project = "cuttlefish"
tenant = "mussel"
job = "winkle"
-
expected = "projects/{project}/tenants/{tenant}/jobs/{job}".format(
project=project, tenant=tenant, job=job,
)
@@ -3153,7 +3289,6 @@ def test_parse_job_path():
def test_tenant_path():
project = "squid"
tenant = "clam"
-
expected = "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@@ -3175,7 +3310,6 @@ def test_parse_tenant_path():
def test_common_billing_account_path():
billing_account = "oyster"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -3196,7 +3330,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "cuttlefish"
-
expected = "folders/{folder}".format(folder=folder,)
actual = JobServiceClient.common_folder_path(folder)
assert expected == actual
@@ -3215,7 +3348,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "winkle"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = JobServiceClient.common_organization_path(organization)
assert expected == actual
@@ -3234,7 +3366,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "scallop"
-
expected = "projects/{project}".format(project=project,)
actual = JobServiceClient.common_project_path(project)
assert expected == actual
@@ -3254,7 +3385,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "squid"
location = "clam"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -3281,7 +3411,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.JobServiceTransport, "_prep_wrapped_messages"
) as prep:
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -3290,6 +3420,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = JobServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4/test_tenant_service.py b/tests/unit/gapic/talent_v4/test_tenant_service.py
index 32438832..fadc80d4 100644
--- a/tests/unit/gapic/talent_v4/test_tenant_service.py
+++ b/tests/unit/gapic/talent_v4/test_tenant_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,23 +23,41 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4.services.tenant_service import TenantServiceAsyncClient
from google.cloud.talent_v4.services.tenant_service import TenantServiceClient
from google.cloud.talent_v4.services.tenant_service import pagers
from google.cloud.talent_v4.services.tenant_service import transports
+from google.cloud.talent_v4.services.tenant_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4.types import tenant
from google.cloud.talent_v4.types import tenant as gct_tenant
from google.cloud.talent_v4.types import tenant_service
from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -88,26 +105,78 @@ def test__get_default_mtls_endpoint():
@pytest.mark.parametrize(
- "client_class", [TenantServiceClient, TenantServiceAsyncClient]
+ "client_class", [TenantServiceClient, TenantServiceAsyncClient,]
+)
+def test_tenant_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [TenantServiceClient, TenantServiceAsyncClient,]
+)
+def test_tenant_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.TenantServiceGrpcTransport, "grpc"),
+ (transports.TenantServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_tenant_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize(
+ "client_class", [TenantServiceClient, TenantServiceAsyncClient,]
)
def test_tenant_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_tenant_service_client_get_transport_class():
transport = TenantServiceClient.get_transport_class()
- assert transport == transports.TenantServiceGrpcTransport
+ available_transports = [
+ transports.TenantServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = TenantServiceClient.get_transport_class("grpc")
assert transport == transports.TenantServiceGrpcTransport
@@ -139,7 +208,7 @@ def test_tenant_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(TenantServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -158,7 +227,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -174,7 +243,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -190,7 +259,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -218,7 +287,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -269,29 +338,25 @@ def test_tenant_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -300,66 +365,53 @@ def test_tenant_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -385,7 +437,7 @@ def test_tenant_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -415,7 +467,7 @@ def test_tenant_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -434,7 +486,7 @@ def test_tenant_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -444,7 +496,7 @@ def test_create_tenant(
transport: str = "grpc", request_type=tenant_service.CreateTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -457,21 +509,16 @@ def test_create_tenant(
call.return_value = gct_tenant.Tenant(
name="name_value", external_id="external_id_value",
)
-
response = client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.CreateTenantRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
@@ -479,12 +526,27 @@ def test_create_tenant_from_dict():
test_create_tenant(request_type=dict)
+def test_create_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
+ client.create_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.CreateTenantRequest()
+
+
@pytest.mark.asyncio
async def test_create_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.CreateTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -497,20 +559,16 @@ async def test_create_tenant_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
gct_tenant.Tenant(name="name_value", external_id="external_id_value",)
)
-
response = await client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.CreateTenantRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
@@ -520,17 +578,17 @@ async def test_create_tenant_async_from_dict():
def test_create_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.CreateTenantRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
call.return_value = gct_tenant.Tenant()
-
client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -545,17 +603,19 @@ def test_create_tenant_field_headers():
@pytest.mark.asyncio
async def test_create_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.CreateTenantRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_tenant.Tenant())
-
await client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -569,13 +629,12 @@ async def test_create_tenant_field_headers_async():
def test_create_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_tenant.Tenant()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_tenant(
@@ -586,14 +645,12 @@ def test_create_tenant_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
def test_create_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -607,7 +664,9 @@ def test_create_tenant_flattened_error():
@pytest.mark.asyncio
async def test_create_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
@@ -625,15 +684,15 @@ async def test_create_tenant_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
@pytest.mark.asyncio
async def test_create_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -649,7 +708,7 @@ def test_get_tenant(
transport: str = "grpc", request_type=tenant_service.GetTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -662,21 +721,16 @@ def test_get_tenant(
call.return_value = tenant.Tenant(
name="name_value", external_id="external_id_value",
)
-
response = client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.GetTenantRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
@@ -684,12 +738,27 @@ def test_get_tenant_from_dict():
test_get_tenant(request_type=dict)
+def test_get_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
+ client.get_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.GetTenantRequest()
+
+
@pytest.mark.asyncio
async def test_get_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.GetTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -702,20 +771,16 @@ async def test_get_tenant_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
tenant.Tenant(name="name_value", external_id="external_id_value",)
)
-
response = await client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.GetTenantRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
@@ -725,17 +790,17 @@ async def test_get_tenant_async_from_dict():
def test_get_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.GetTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
call.return_value = tenant.Tenant()
-
client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -750,17 +815,19 @@ def test_get_tenant_field_headers():
@pytest.mark.asyncio
async def test_get_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.GetTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tenant.Tenant())
-
await client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -774,13 +841,12 @@ async def test_get_tenant_field_headers_async():
def test_get_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = tenant.Tenant()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_tenant(name="name_value",)
@@ -789,12 +855,11 @@ def test_get_tenant_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -806,7 +871,9 @@ def test_get_tenant_flattened_error():
@pytest.mark.asyncio
async def test_get_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
@@ -822,13 +889,14 @@ async def test_get_tenant_flattened_async():
# 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_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -842,7 +910,7 @@ def test_update_tenant(
transport: str = "grpc", request_type=tenant_service.UpdateTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -855,21 +923,16 @@ def test_update_tenant(
call.return_value = gct_tenant.Tenant(
name="name_value", external_id="external_id_value",
)
-
response = client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.UpdateTenantRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
@@ -877,12 +940,27 @@ def test_update_tenant_from_dict():
test_update_tenant(request_type=dict)
+def test_update_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
+ client.update_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.UpdateTenantRequest()
+
+
@pytest.mark.asyncio
async def test_update_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.UpdateTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -895,20 +973,16 @@ async def test_update_tenant_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
gct_tenant.Tenant(name="name_value", external_id="external_id_value",)
)
-
response = await client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.UpdateTenantRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
@@ -918,17 +992,17 @@ async def test_update_tenant_async_from_dict():
def test_update_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.UpdateTenantRequest()
+
request.tenant.name = "tenant.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
call.return_value = gct_tenant.Tenant()
-
client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -943,17 +1017,19 @@ def test_update_tenant_field_headers():
@pytest.mark.asyncio
async def test_update_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.UpdateTenantRequest()
+
request.tenant.name = "tenant.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_tenant.Tenant())
-
await client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -967,32 +1043,29 @@ async def test_update_tenant_field_headers_async():
def test_update_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_tenant.Tenant()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_tenant(
tenant=gct_tenant.Tenant(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
-
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+ assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"])
def test_update_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1000,13 +1073,15 @@ def test_update_tenant_flattened_error():
client.update_tenant(
tenant_service.UpdateTenantRequest(),
tenant=gct_tenant.Tenant(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@pytest.mark.asyncio
async def test_update_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
@@ -1018,22 +1093,22 @@ async def test_update_tenant_flattened_async():
# using the keyword arguments to the method.
response = await client.update_tenant(
tenant=gct_tenant.Tenant(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
-
- assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+ assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"])
@pytest.mark.asyncio
async def test_update_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1041,7 +1116,7 @@ async def test_update_tenant_flattened_error_async():
await client.update_tenant(
tenant_service.UpdateTenantRequest(),
tenant=gct_tenant.Tenant(name="name_value"),
- update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
@@ -1049,7 +1124,7 @@ def test_delete_tenant(
transport: str = "grpc", request_type=tenant_service.DeleteTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1060,13 +1135,11 @@ def test_delete_tenant(
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.DeleteTenantRequest()
# Establish that the response is the type that we expect.
@@ -1077,12 +1150,27 @@ def test_delete_tenant_from_dict():
test_delete_tenant(request_type=dict)
+def test_delete_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
+ client.delete_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.DeleteTenantRequest()
+
+
@pytest.mark.asyncio
async def test_delete_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.DeleteTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1093,13 +1181,11 @@ async def test_delete_tenant_async(
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.DeleteTenantRequest()
# Establish that the response is the type that we expect.
@@ -1112,17 +1198,17 @@ async def test_delete_tenant_async_from_dict():
def test_delete_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.DeleteTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
call.return_value = None
-
client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -1137,17 +1223,19 @@ def test_delete_tenant_field_headers():
@pytest.mark.asyncio
async def test_delete_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.DeleteTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -1161,13 +1249,12 @@ async def test_delete_tenant_field_headers_async():
def test_delete_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__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_tenant(name="name_value",)
@@ -1176,12 +1263,11 @@ def test_delete_tenant_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1193,7 +1279,9 @@ def test_delete_tenant_flattened_error():
@pytest.mark.asyncio
async def test_delete_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
@@ -1209,13 +1297,14 @@ async def test_delete_tenant_flattened_async():
# 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_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1229,7 +1318,7 @@ def test_list_tenants(
transport: str = "grpc", request_type=tenant_service.ListTenantsRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1242,19 +1331,15 @@ def test_list_tenants(
call.return_value = tenant_service.ListTenantsResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.ListTenantsRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListTenantsPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1262,12 +1347,27 @@ def test_list_tenants_from_dict():
test_list_tenants(request_type=dict)
+def test_list_tenants_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
+ client.list_tenants()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.ListTenantsRequest()
+
+
@pytest.mark.asyncio
async def test_list_tenants_async(
transport: str = "grpc_asyncio", request_type=tenant_service.ListTenantsRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1280,18 +1380,15 @@ async def test_list_tenants_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
tenant_service.ListTenantsResponse(next_page_token="next_page_token_value",)
)
-
response = await client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.ListTenantsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListTenantsAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1301,17 +1398,17 @@ async def test_list_tenants_async_from_dict():
def test_list_tenants_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.ListTenantsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
call.return_value = tenant_service.ListTenantsResponse()
-
client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
@@ -1326,11 +1423,14 @@ def test_list_tenants_field_headers():
@pytest.mark.asyncio
async def test_list_tenants_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.ListTenantsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1338,7 +1438,6 @@ async def test_list_tenants_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
tenant_service.ListTenantsResponse()
)
-
await client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
@@ -1352,13 +1451,12 @@ async def test_list_tenants_field_headers_async():
def test_list_tenants_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = tenant_service.ListTenantsResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_tenants(parent="parent_value",)
@@ -1367,12 +1465,11 @@ def test_list_tenants_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
def test_list_tenants_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1384,7 +1481,9 @@ def test_list_tenants_flattened_error():
@pytest.mark.asyncio
async def test_list_tenants_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
@@ -1402,13 +1501,14 @@ async def test_list_tenants_flattened_async():
# 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_tenants_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1419,7 +1519,7 @@ async def test_list_tenants_flattened_error_async():
def test_list_tenants_pager():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
@@ -1453,7 +1553,7 @@ def test_list_tenants_pager():
def test_list_tenants_pages():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
@@ -1479,7 +1579,7 @@ def test_list_tenants_pages():
@pytest.mark.asyncio
async def test_list_tenants_async_pager():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1512,7 +1612,7 @@ async def test_list_tenants_async_pager():
@pytest.mark.asyncio
async def test_list_tenants_async_pages():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1543,16 +1643,16 @@ async def test_list_tenants_async_pages():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TenantServiceClient(
@@ -1562,7 +1662,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TenantServiceClient(
@@ -1573,7 +1673,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = TenantServiceClient(transport=transport)
assert client.transport is transport
@@ -1582,13 +1682,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.TenantServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -1603,23 +1703,23 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.TenantServiceGrpcTransport,)
def test_tenant_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.TenantServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -1631,7 +1731,7 @@ def test_tenant_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.TenantServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -1648,15 +1748,40 @@ def test_tenant_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_tenant_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4.services.tenant_service.transports.TenantServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.TenantServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_tenant_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4.services.tenant_service.transports.TenantServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.TenantServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -1672,19 +1797,36 @@ def test_tenant_service_base_transport_with_credentials_file():
def test_tenant_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4.services.tenant_service.transports.TenantServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.TenantServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_tenant_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ TenantServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_tenant_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
TenantServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -1695,14 +1837,44 @@ def test_tenant_service_auth_adc():
)
-def test_tenant_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TenantServiceGrpcTransport,
+ transports.TenantServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_tenant_service_transport_auth_adc(transport_class):
# 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.TenantServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TenantServiceGrpcTransport,
+ transports.TenantServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_tenant_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -1712,9 +1884,92 @@ def test_tenant_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.TenantServiceGrpcTransport, grpc_helpers),
+ (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_tenant_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TenantServiceGrpcTransport,
+ transports.TenantServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_tenant_service_host_no_port():
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -1722,7 +1977,7 @@ def test_tenant_service_host_no_port():
def test_tenant_service_host_with_port():
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -1731,7 +1986,7 @@ def test_tenant_service_host_with_port():
def test_tenant_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.TenantServiceGrpcTransport(
@@ -1743,7 +1998,7 @@ def test_tenant_service_grpc_transport_channel():
def test_tenant_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.TenantServiceGrpcAsyncIOTransport(
@@ -1754,6 +2009,8 @@ def test_tenant_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -1766,7 +2023,7 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -1774,9 +2031,9 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -1792,10 +2049,7 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -1807,6 +2061,8 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -1822,7 +2078,7 @@ def test_tenant_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -1840,10 +2096,7 @@ def test_tenant_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -1857,7 +2110,6 @@ def test_tenant_service_transport_channel_mtls_with_adc(transport_class):
def test_tenant_path():
project = "squid"
tenant = "clam"
-
expected = "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@@ -1879,7 +2131,6 @@ def test_parse_tenant_path():
def test_common_billing_account_path():
billing_account = "oyster"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -1900,7 +2151,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "cuttlefish"
-
expected = "folders/{folder}".format(folder=folder,)
actual = TenantServiceClient.common_folder_path(folder)
assert expected == actual
@@ -1919,7 +2169,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "winkle"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = TenantServiceClient.common_organization_path(organization)
assert expected == actual
@@ -1938,7 +2187,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "scallop"
-
expected = "projects/{project}".format(project=project,)
actual = TenantServiceClient.common_project_path(project)
assert expected == actual
@@ -1958,7 +2206,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "squid"
location = "clam"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -1985,7 +2232,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.TenantServiceTransport, "_prep_wrapped_messages"
) as prep:
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -1994,6 +2241,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = TenantServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4beta1/__init__.py b/tests/unit/gapic/talent_v4beta1/__init__.py
index 8b137891..4de65971 100644
--- a/tests/unit/gapic/talent_v4beta1/__init__.py
+++ b/tests/unit/gapic/talent_v4beta1/__init__.py
@@ -1 +1,15 @@
-
+# -*- coding: utf-8 -*-
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/tests/unit/gapic/talent_v4beta1/test_application_service.py b/tests/unit/gapic/talent_v4beta1/test_application_service.py
index 9504a896..7f6937fb 100644
--- a/tests/unit/gapic/talent_v4beta1/test_application_service.py
+++ b/tests/unit/gapic/talent_v4beta1/test_application_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,13 +23,13 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4beta1.services.application_service import (
ApplicationServiceAsyncClient,
@@ -40,15 +39,33 @@
)
from google.cloud.talent_v4beta1.services.application_service import pagers
from google.cloud.talent_v4beta1.services.application_service import transports
+from google.cloud.talent_v4beta1.services.application_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4beta1.types import application
from google.cloud.talent_v4beta1.types import application as gct_application
from google.cloud.talent_v4beta1.types import application_service
from google.cloud.talent_v4beta1.types import common
from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -97,26 +114,78 @@ def test__get_default_mtls_endpoint():
@pytest.mark.parametrize(
- "client_class", [ApplicationServiceClient, ApplicationServiceAsyncClient]
+ "client_class", [ApplicationServiceClient, ApplicationServiceAsyncClient,]
+)
+def test_application_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [ApplicationServiceClient, ApplicationServiceAsyncClient,]
+)
+def test_application_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.ApplicationServiceGrpcTransport, "grpc"),
+ (transports.ApplicationServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_application_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize(
+ "client_class", [ApplicationServiceClient, ApplicationServiceAsyncClient,]
)
def test_application_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_application_service_client_get_transport_class():
transport = ApplicationServiceClient.get_transport_class()
- assert transport == transports.ApplicationServiceGrpcTransport
+ available_transports = [
+ transports.ApplicationServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = ApplicationServiceClient.get_transport_class("grpc")
assert transport == transports.ApplicationServiceGrpcTransport
@@ -148,7 +217,7 @@ def test_application_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(ApplicationServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -167,7 +236,7 @@ def test_application_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -183,7 +252,7 @@ def test_application_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -199,7 +268,7 @@ def test_application_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -227,7 +296,7 @@ def test_application_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -288,29 +357,25 @@ def test_application_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -319,66 +384,53 @@ def test_application_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -404,7 +456,7 @@ def test_application_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -434,7 +486,7 @@ def test_application_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -453,7 +505,7 @@ def test_application_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -463,7 +515,7 @@ def test_create_application(
transport: str = "grpc", request_type=application_service.CreateApplicationRequest
):
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -487,37 +539,24 @@ def test_create_application(
outcome=common.Outcome.POSITIVE,
job_title_snippet="job_title_snippet_value",
)
-
response = client.create_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.CreateApplicationRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_application.Application)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.profile == "profile_value"
-
assert response.job == "job_value"
-
assert response.company == "company_value"
-
assert response.stage == gct_application.Application.ApplicationStage.NEW
-
assert response.state == gct_application.Application.ApplicationState.IN_PROGRESS
-
assert response.outcome_notes == "outcome_notes_value"
-
assert response.outcome == common.Outcome.POSITIVE
-
assert response.job_title_snippet == "job_title_snippet_value"
@@ -525,13 +564,30 @@ def test_create_application_from_dict():
test_create_application(request_type=dict)
+def test_create_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_application), "__call__"
+ ) as call:
+ client.create_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == application_service.CreateApplicationRequest()
+
+
@pytest.mark.asyncio
async def test_create_application_async(
transport: str = "grpc_asyncio",
request_type=application_service.CreateApplicationRequest,
):
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -557,36 +613,24 @@ async def test_create_application_async(
job_title_snippet="job_title_snippet_value",
)
)
-
response = await client.create_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.CreateApplicationRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_application.Application)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.profile == "profile_value"
-
assert response.job == "job_value"
-
assert response.company == "company_value"
-
assert response.stage == gct_application.Application.ApplicationStage.NEW
-
assert response.state == gct_application.Application.ApplicationState.IN_PROGRESS
-
assert response.outcome_notes == "outcome_notes_value"
-
assert response.outcome == common.Outcome.POSITIVE
-
assert response.job_title_snippet == "job_title_snippet_value"
@@ -596,11 +640,14 @@ async def test_create_application_async_from_dict():
def test_create_application_field_headers():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.CreateApplicationRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -608,7 +655,6 @@ def test_create_application_field_headers():
type(client.transport.create_application), "__call__"
) as call:
call.return_value = gct_application.Application()
-
client.create_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -624,12 +670,13 @@ def test_create_application_field_headers():
@pytest.mark.asyncio
async def test_create_application_field_headers_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.CreateApplicationRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -639,7 +686,6 @@ async def test_create_application_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
gct_application.Application()
)
-
await client.create_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -653,7 +699,9 @@ async def test_create_application_field_headers_async():
def test_create_application_flattened():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -661,7 +709,6 @@ def test_create_application_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = gct_application.Application()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_application(
@@ -673,14 +720,14 @@ def test_create_application_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].application == gct_application.Application(name="name_value")
def test_create_application_flattened_error():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -695,7 +742,7 @@ def test_create_application_flattened_error():
@pytest.mark.asyncio
async def test_create_application_flattened_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -719,16 +766,14 @@ async def test_create_application_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].application == gct_application.Application(name="name_value")
@pytest.mark.asyncio
async def test_create_application_flattened_error_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -745,7 +790,7 @@ def test_get_application(
transport: str = "grpc", request_type=application_service.GetApplicationRequest
):
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -767,37 +812,24 @@ def test_get_application(
outcome=common.Outcome.POSITIVE,
job_title_snippet="job_title_snippet_value",
)
-
response = client.get_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.GetApplicationRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, application.Application)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.profile == "profile_value"
-
assert response.job == "job_value"
-
assert response.company == "company_value"
-
assert response.stage == application.Application.ApplicationStage.NEW
-
assert response.state == application.Application.ApplicationState.IN_PROGRESS
-
assert response.outcome_notes == "outcome_notes_value"
-
assert response.outcome == common.Outcome.POSITIVE
-
assert response.job_title_snippet == "job_title_snippet_value"
@@ -805,13 +837,28 @@ def test_get_application_from_dict():
test_get_application(request_type=dict)
+def test_get_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_application), "__call__") as call:
+ client.get_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == application_service.GetApplicationRequest()
+
+
@pytest.mark.asyncio
async def test_get_application_async(
transport: str = "grpc_asyncio",
request_type=application_service.GetApplicationRequest,
):
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -835,36 +882,24 @@ async def test_get_application_async(
job_title_snippet="job_title_snippet_value",
)
)
-
response = await client.get_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.GetApplicationRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, application.Application)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.profile == "profile_value"
-
assert response.job == "job_value"
-
assert response.company == "company_value"
-
assert response.stage == application.Application.ApplicationStage.NEW
-
assert response.state == application.Application.ApplicationState.IN_PROGRESS
-
assert response.outcome_notes == "outcome_notes_value"
-
assert response.outcome == common.Outcome.POSITIVE
-
assert response.job_title_snippet == "job_title_snippet_value"
@@ -874,17 +909,19 @@ async def test_get_application_async_from_dict():
def test_get_application_field_headers():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.GetApplicationRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_application), "__call__") as call:
call.return_value = application.Application()
-
client.get_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -900,12 +937,13 @@ def test_get_application_field_headers():
@pytest.mark.asyncio
async def test_get_application_field_headers_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.GetApplicationRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -913,7 +951,6 @@ async def test_get_application_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
application.Application()
)
-
await client.get_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -927,13 +964,14 @@ async def test_get_application_field_headers_async():
def test_get_application_flattened():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_application), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = application.Application()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_application(name="name_value",)
@@ -942,12 +980,13 @@ def test_get_application_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_application_flattened_error():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -960,7 +999,7 @@ def test_get_application_flattened_error():
@pytest.mark.asyncio
async def test_get_application_flattened_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -979,14 +1018,13 @@ async def test_get_application_flattened_async():
# 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_application_flattened_error_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1001,7 +1039,7 @@ def test_update_application(
transport: str = "grpc", request_type=application_service.UpdateApplicationRequest
):
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1025,37 +1063,24 @@ def test_update_application(
outcome=common.Outcome.POSITIVE,
job_title_snippet="job_title_snippet_value",
)
-
response = client.update_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.UpdateApplicationRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_application.Application)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.profile == "profile_value"
-
assert response.job == "job_value"
-
assert response.company == "company_value"
-
assert response.stage == gct_application.Application.ApplicationStage.NEW
-
assert response.state == gct_application.Application.ApplicationState.IN_PROGRESS
-
assert response.outcome_notes == "outcome_notes_value"
-
assert response.outcome == common.Outcome.POSITIVE
-
assert response.job_title_snippet == "job_title_snippet_value"
@@ -1063,13 +1088,30 @@ def test_update_application_from_dict():
test_update_application(request_type=dict)
+def test_update_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_application), "__call__"
+ ) as call:
+ client.update_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == application_service.UpdateApplicationRequest()
+
+
@pytest.mark.asyncio
async def test_update_application_async(
transport: str = "grpc_asyncio",
request_type=application_service.UpdateApplicationRequest,
):
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1095,36 +1137,24 @@ async def test_update_application_async(
job_title_snippet="job_title_snippet_value",
)
)
-
response = await client.update_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.UpdateApplicationRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_application.Application)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.profile == "profile_value"
-
assert response.job == "job_value"
-
assert response.company == "company_value"
-
assert response.stage == gct_application.Application.ApplicationStage.NEW
-
assert response.state == gct_application.Application.ApplicationState.IN_PROGRESS
-
assert response.outcome_notes == "outcome_notes_value"
-
assert response.outcome == common.Outcome.POSITIVE
-
assert response.job_title_snippet == "job_title_snippet_value"
@@ -1134,11 +1164,14 @@ async def test_update_application_async_from_dict():
def test_update_application_field_headers():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.UpdateApplicationRequest()
+
request.application.name = "application.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1146,7 +1179,6 @@ def test_update_application_field_headers():
type(client.transport.update_application), "__call__"
) as call:
call.return_value = gct_application.Application()
-
client.update_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -1164,12 +1196,13 @@ def test_update_application_field_headers():
@pytest.mark.asyncio
async def test_update_application_field_headers_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.UpdateApplicationRequest()
+
request.application.name = "application.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1179,7 +1212,6 @@ async def test_update_application_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
gct_application.Application()
)
-
await client.update_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -1195,7 +1227,9 @@ async def test_update_application_field_headers_async():
def test_update_application_flattened():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1203,7 +1237,6 @@ def test_update_application_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = gct_application.Application()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_application(
@@ -1214,12 +1247,13 @@ def test_update_application_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].application == gct_application.Application(name="name_value")
def test_update_application_flattened_error():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1233,7 +1267,7 @@ def test_update_application_flattened_error():
@pytest.mark.asyncio
async def test_update_application_flattened_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1256,14 +1290,13 @@ async def test_update_application_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].application == gct_application.Application(name="name_value")
@pytest.mark.asyncio
async def test_update_application_flattened_error_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1279,7 +1312,7 @@ def test_delete_application(
transport: str = "grpc", request_type=application_service.DeleteApplicationRequest
):
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1292,13 +1325,11 @@ def test_delete_application(
) as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.DeleteApplicationRequest()
# Establish that the response is the type that we expect.
@@ -1309,13 +1340,30 @@ def test_delete_application_from_dict():
test_delete_application(request_type=dict)
+def test_delete_application_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_application), "__call__"
+ ) as call:
+ client.delete_application()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == application_service.DeleteApplicationRequest()
+
+
@pytest.mark.asyncio
async def test_delete_application_async(
transport: str = "grpc_asyncio",
request_type=application_service.DeleteApplicationRequest,
):
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1328,13 +1376,11 @@ async def test_delete_application_async(
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_application(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.DeleteApplicationRequest()
# Establish that the response is the type that we expect.
@@ -1347,11 +1393,14 @@ async def test_delete_application_async_from_dict():
def test_delete_application_field_headers():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.DeleteApplicationRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1359,7 +1408,6 @@ def test_delete_application_field_headers():
type(client.transport.delete_application), "__call__"
) as call:
call.return_value = None
-
client.delete_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -1375,12 +1423,13 @@ def test_delete_application_field_headers():
@pytest.mark.asyncio
async def test_delete_application_field_headers_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.DeleteApplicationRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1388,7 +1437,6 @@ async def test_delete_application_field_headers_async():
type(client.transport.delete_application), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_application(request)
# Establish that the underlying gRPC stub method was called.
@@ -1402,7 +1450,9 @@ async def test_delete_application_field_headers_async():
def test_delete_application_flattened():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1410,7 +1460,6 @@ def test_delete_application_flattened():
) 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_application(name="name_value",)
@@ -1419,12 +1468,13 @@ def test_delete_application_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_application_flattened_error():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1437,7 +1487,7 @@ def test_delete_application_flattened_error():
@pytest.mark.asyncio
async def test_delete_application_flattened_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1456,14 +1506,13 @@ async def test_delete_application_flattened_async():
# 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_application_flattened_error_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1478,7 +1527,7 @@ def test_list_applications(
transport: str = "grpc", request_type=application_service.ListApplicationsRequest
):
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1493,19 +1542,15 @@ def test_list_applications(
call.return_value = application_service.ListApplicationsResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_applications(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.ListApplicationsRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListApplicationsPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1513,13 +1558,30 @@ def test_list_applications_from_dict():
test_list_applications(request_type=dict)
+def test_list_applications_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_applications), "__call__"
+ ) as call:
+ client.list_applications()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == application_service.ListApplicationsRequest()
+
+
@pytest.mark.asyncio
async def test_list_applications_async(
transport: str = "grpc_asyncio",
request_type=application_service.ListApplicationsRequest,
):
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1536,18 +1598,15 @@ async def test_list_applications_async(
next_page_token="next_page_token_value",
)
)
-
response = await client.list_applications(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == application_service.ListApplicationsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListApplicationsAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1557,11 +1616,14 @@ async def test_list_applications_async_from_dict():
def test_list_applications_field_headers():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.ListApplicationsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1569,7 +1631,6 @@ def test_list_applications_field_headers():
type(client.transport.list_applications), "__call__"
) as call:
call.return_value = application_service.ListApplicationsResponse()
-
client.list_applications(request)
# Establish that the underlying gRPC stub method was called.
@@ -1585,12 +1646,13 @@ def test_list_applications_field_headers():
@pytest.mark.asyncio
async def test_list_applications_field_headers_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = application_service.ListApplicationsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1600,7 +1662,6 @@ async def test_list_applications_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
application_service.ListApplicationsResponse()
)
-
await client.list_applications(request)
# Establish that the underlying gRPC stub method was called.
@@ -1614,7 +1675,9 @@ async def test_list_applications_field_headers_async():
def test_list_applications_flattened():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1622,7 +1685,6 @@ def test_list_applications_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = application_service.ListApplicationsResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_applications(parent="parent_value",)
@@ -1631,12 +1693,13 @@ def test_list_applications_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
def test_list_applications_flattened_error():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1649,7 +1712,7 @@ def test_list_applications_flattened_error():
@pytest.mark.asyncio
async def test_list_applications_flattened_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1670,14 +1733,13 @@ async def test_list_applications_flattened_async():
# 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_applications_flattened_error_async():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
@@ -1689,7 +1751,7 @@ async def test_list_applications_flattened_error_async():
def test_list_applications_pager():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = ApplicationServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1731,7 +1793,7 @@ def test_list_applications_pager():
def test_list_applications_pages():
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = ApplicationServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1766,7 +1828,7 @@ def test_list_applications_pages():
@pytest.mark.asyncio
async def test_list_applications_async_pager():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1809,7 +1871,7 @@ async def test_list_applications_async_pager():
@pytest.mark.asyncio
async def test_list_applications_async_pages():
client = ApplicationServiceAsyncClient(
- credentials=credentials.AnonymousCredentials,
+ credentials=ga_credentials.AnonymousCredentials,
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1849,16 +1911,16 @@ async def test_list_applications_async_pages():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.ApplicationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.ApplicationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = ApplicationServiceClient(
@@ -1868,7 +1930,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.ApplicationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = ApplicationServiceClient(
@@ -1879,7 +1941,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.ApplicationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = ApplicationServiceClient(transport=transport)
assert client.transport is transport
@@ -1888,13 +1950,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.ApplicationServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.ApplicationServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -1909,23 +1971,25 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = ApplicationServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ApplicationServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
assert isinstance(client.transport, transports.ApplicationServiceGrpcTransport,)
def test_application_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.ApplicationServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -1937,7 +2001,7 @@ def test_application_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.ApplicationServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -1954,15 +2018,40 @@ def test_application_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_application_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4beta1.services.application_service.transports.ApplicationServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.ApplicationServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_application_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4beta1.services.application_service.transports.ApplicationServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.ApplicationServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -1978,19 +2067,36 @@ def test_application_service_base_transport_with_credentials_file():
def test_application_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4beta1.services.application_service.transports.ApplicationServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.ApplicationServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_application_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ ApplicationServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_application_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
ApplicationServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -2001,14 +2107,44 @@ def test_application_service_auth_adc():
)
-def test_application_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ApplicationServiceGrpcTransport,
+ transports.ApplicationServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_application_service_transport_auth_adc(transport_class):
# 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.ApplicationServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ApplicationServiceGrpcTransport,
+ transports.ApplicationServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_application_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -2018,9 +2154,94 @@ def test_application_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.ApplicationServiceGrpcTransport, grpc_helpers),
+ (transports.ApplicationServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_application_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ApplicationServiceGrpcTransport,
+ transports.ApplicationServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_application_service_grpc_transport_client_cert_source_for_mtls(
+ transport_class,
+):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_application_service_host_no_port():
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -2028,7 +2249,7 @@ def test_application_service_host_no_port():
def test_application_service_host_with_port():
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -2037,7 +2258,7 @@ def test_application_service_host_with_port():
def test_application_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.ApplicationServiceGrpcTransport(
@@ -2049,7 +2270,7 @@ def test_application_service_grpc_transport_channel():
def test_application_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.ApplicationServiceGrpcAsyncIOTransport(
@@ -2060,6 +2281,8 @@ def test_application_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -2074,7 +2297,7 @@ def test_application_service_transport_channel_mtls_with_client_cert_source(
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -2082,9 +2305,9 @@ def test_application_service_transport_channel_mtls_with_client_cert_source(
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -2100,10 +2323,7 @@ def test_application_service_transport_channel_mtls_with_client_cert_source(
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2115,6 +2335,8 @@ def test_application_service_transport_channel_mtls_with_client_cert_source(
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -2130,7 +2352,7 @@ def test_application_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -2148,10 +2370,7 @@ def test_application_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2167,7 +2386,6 @@ def test_application_path():
tenant = "clam"
profile = "whelk"
application = "octopus"
-
expected = "projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}".format(
project=project, tenant=tenant, profile=profile, application=application,
)
@@ -2195,7 +2413,6 @@ def test_company_path():
project = "winkle"
tenant = "nautilus"
company = "scallop"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -2220,7 +2437,6 @@ def test_job_path():
project = "whelk"
tenant = "octopus"
job = "oyster"
-
expected = "projects/{project}/tenants/{tenant}/jobs/{job}".format(
project=project, tenant=tenant, job=job,
)
@@ -2245,7 +2461,6 @@ def test_profile_path():
project = "winkle"
tenant = "nautilus"
profile = "scallop"
-
expected = "projects/{project}/tenants/{tenant}/profiles/{profile}".format(
project=project, tenant=tenant, profile=profile,
)
@@ -2268,7 +2483,6 @@ def test_parse_profile_path():
def test_common_billing_account_path():
billing_account = "whelk"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -2289,7 +2503,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "oyster"
-
expected = "folders/{folder}".format(folder=folder,)
actual = ApplicationServiceClient.common_folder_path(folder)
assert expected == actual
@@ -2308,7 +2521,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "cuttlefish"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = ApplicationServiceClient.common_organization_path(organization)
assert expected == actual
@@ -2327,7 +2539,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "winkle"
-
expected = "projects/{project}".format(project=project,)
actual = ApplicationServiceClient.common_project_path(project)
assert expected == actual
@@ -2347,7 +2558,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "scallop"
location = "abalone"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -2374,7 +2584,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.ApplicationServiceTransport, "_prep_wrapped_messages"
) as prep:
client = ApplicationServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -2383,6 +2593,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = ApplicationServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4beta1/test_company_service.py b/tests/unit/gapic/talent_v4beta1/test_company_service.py
index 603a1904..ab5c4501 100644
--- a/tests/unit/gapic/talent_v4beta1/test_company_service.py
+++ b/tests/unit/gapic/talent_v4beta1/test_company_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,13 +23,13 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4beta1.services.company_service import (
CompanyServiceAsyncClient,
@@ -38,14 +37,32 @@
from google.cloud.talent_v4beta1.services.company_service import CompanyServiceClient
from google.cloud.talent_v4beta1.services.company_service import pagers
from google.cloud.talent_v4beta1.services.company_service import transports
+from google.cloud.talent_v4beta1.services.company_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import company
from google.cloud.talent_v4beta1.types import company as gct_company
from google.cloud.talent_v4beta1.types import company_service
from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import postal_address_pb2 as postal_address # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -93,26 +110,78 @@ def test__get_default_mtls_endpoint():
@pytest.mark.parametrize(
- "client_class", [CompanyServiceClient, CompanyServiceAsyncClient]
+ "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,]
+)
+def test_company_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,]
+)
+def test_company_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.CompanyServiceGrpcTransport, "grpc"),
+ (transports.CompanyServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_company_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize(
+ "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,]
)
def test_company_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_company_service_client_get_transport_class():
transport = CompanyServiceClient.get_transport_class()
- assert transport == transports.CompanyServiceGrpcTransport
+ available_transports = [
+ transports.CompanyServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = CompanyServiceClient.get_transport_class("grpc")
assert transport == transports.CompanyServiceGrpcTransport
@@ -144,7 +213,7 @@ def test_company_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(CompanyServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -163,7 +232,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -179,7 +248,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -195,7 +264,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -223,7 +292,7 @@ def test_company_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -274,29 +343,25 @@ def test_company_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -305,66 +370,53 @@ def test_company_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -390,7 +442,7 @@ def test_company_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -420,7 +472,7 @@ def test_company_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -439,7 +491,7 @@ def test_company_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -449,7 +501,7 @@ def test_create_company(
transport: str = "grpc", request_type=company_service.CreateCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -475,43 +527,28 @@ def test_create_company(
],
suspended=True,
)
-
response = client.create_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.CreateCompanyRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -519,12 +556,27 @@ def test_create_company_from_dict():
test_create_company(request_type=dict)
+def test_create_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_company), "__call__") as call:
+ client.create_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.CreateCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_create_company_async(
transport: str = "grpc_asyncio", request_type=company_service.CreateCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -552,42 +604,28 @@ async def test_create_company_async(
suspended=True,
)
)
-
response = await client.create_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.CreateCompanyRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -597,17 +635,17 @@ async def test_create_company_async_from_dict():
def test_create_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.CreateCompanyRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
call.return_value = gct_company.Company()
-
client.create_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -622,17 +660,19 @@ def test_create_company_field_headers():
@pytest.mark.asyncio
async def test_create_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.CreateCompanyRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_company.Company())
-
await client.create_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -646,13 +686,12 @@ async def test_create_company_field_headers_async():
def test_create_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_company.Company()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_company(
@@ -663,14 +702,12 @@ def test_create_company_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].company == gct_company.Company(name="name_value")
def test_create_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -684,7 +721,9 @@ def test_create_company_flattened_error():
@pytest.mark.asyncio
async def test_create_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_company), "__call__") as call:
@@ -702,15 +741,15 @@ async def test_create_company_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].company == gct_company.Company(name="name_value")
@pytest.mark.asyncio
async def test_create_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -726,7 +765,7 @@ def test_get_company(
transport: str = "grpc", request_type=company_service.GetCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -752,43 +791,28 @@ def test_get_company(
],
suspended=True,
)
-
response = client.get_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.GetCompanyRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -796,12 +820,27 @@ def test_get_company_from_dict():
test_get_company(request_type=dict)
+def test_get_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_company), "__call__") as call:
+ client.get_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.GetCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_get_company_async(
transport: str = "grpc_asyncio", request_type=company_service.GetCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -829,42 +868,28 @@ async def test_get_company_async(
suspended=True,
)
)
-
response = await client.get_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.GetCompanyRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -874,17 +899,17 @@ async def test_get_company_async_from_dict():
def test_get_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.GetCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
call.return_value = company.Company()
-
client.get_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -899,17 +924,19 @@ def test_get_company_field_headers():
@pytest.mark.asyncio
async def test_get_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.GetCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(company.Company())
-
await client.get_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -923,13 +950,12 @@ async def test_get_company_field_headers_async():
def test_get_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = company.Company()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_company(name="name_value",)
@@ -938,12 +964,11 @@ def test_get_company_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -955,7 +980,9 @@ def test_get_company_flattened_error():
@pytest.mark.asyncio
async def test_get_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_company), "__call__") as call:
@@ -971,13 +998,14 @@ async def test_get_company_flattened_async():
# 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_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -991,7 +1019,7 @@ def test_update_company(
transport: str = "grpc", request_type=company_service.UpdateCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1017,43 +1045,28 @@ def test_update_company(
],
suspended=True,
)
-
response = client.update_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.UpdateCompanyRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -1061,12 +1074,27 @@ def test_update_company_from_dict():
test_update_company(request_type=dict)
+def test_update_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_company), "__call__") as call:
+ client.update_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.UpdateCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_update_company_async(
transport: str = "grpc_asyncio", request_type=company_service.UpdateCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1094,42 +1122,28 @@ async def test_update_company_async(
suspended=True,
)
)
-
response = await client.update_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.UpdateCompanyRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_company.Company)
-
assert response.name == "name_value"
-
assert response.display_name == "display_name_value"
-
assert response.external_id == "external_id_value"
-
assert response.size == common.CompanySize.MINI
-
assert response.headquarters_address == "headquarters_address_value"
-
assert response.hiring_agency is True
-
assert response.eeo_text == "eeo_text_value"
-
assert response.website_uri == "website_uri_value"
-
assert response.career_site_uri == "career_site_uri_value"
-
assert response.image_uri == "image_uri_value"
-
assert response.keyword_searchable_job_custom_attributes == [
"keyword_searchable_job_custom_attributes_value"
]
-
assert response.suspended is True
@@ -1139,17 +1153,17 @@ async def test_update_company_async_from_dict():
def test_update_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.UpdateCompanyRequest()
+
request.company.name = "company.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
call.return_value = gct_company.Company()
-
client.update_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1166,17 +1180,19 @@ def test_update_company_field_headers():
@pytest.mark.asyncio
async def test_update_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.UpdateCompanyRequest()
+
request.company.name = "company.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_company.Company())
-
await client.update_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1192,13 +1208,12 @@ async def test_update_company_field_headers_async():
def test_update_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_company.Company()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_company(company=gct_company.Company(name="name_value"),)
@@ -1207,12 +1222,11 @@ def test_update_company_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].company == gct_company.Company(name="name_value")
def test_update_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1225,7 +1239,9 @@ def test_update_company_flattened_error():
@pytest.mark.asyncio
async def test_update_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_company), "__call__") as call:
@@ -1243,13 +1259,14 @@ async def test_update_company_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].company == gct_company.Company(name="name_value")
@pytest.mark.asyncio
async def test_update_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1264,7 +1281,7 @@ def test_delete_company(
transport: str = "grpc", request_type=company_service.DeleteCompanyRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1275,13 +1292,11 @@ def test_delete_company(
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.DeleteCompanyRequest()
# Establish that the response is the type that we expect.
@@ -1292,12 +1307,27 @@ def test_delete_company_from_dict():
test_delete_company(request_type=dict)
+def test_delete_company_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
+ client.delete_company()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.DeleteCompanyRequest()
+
+
@pytest.mark.asyncio
async def test_delete_company_async(
transport: str = "grpc_asyncio", request_type=company_service.DeleteCompanyRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1308,13 +1338,11 @@ async def test_delete_company_async(
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.DeleteCompanyRequest()
# Establish that the response is the type that we expect.
@@ -1327,17 +1355,17 @@ async def test_delete_company_async_from_dict():
def test_delete_company_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.DeleteCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
call.return_value = None
-
client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1352,17 +1380,19 @@ def test_delete_company_field_headers():
@pytest.mark.asyncio
async def test_delete_company_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.DeleteCompanyRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_company(request)
# Establish that the underlying gRPC stub method was called.
@@ -1376,13 +1406,12 @@ async def test_delete_company_field_headers_async():
def test_delete_company_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__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_company(name="name_value",)
@@ -1391,12 +1420,11 @@ def test_delete_company_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_company_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1408,7 +1436,9 @@ def test_delete_company_flattened_error():
@pytest.mark.asyncio
async def test_delete_company_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_company), "__call__") as call:
@@ -1424,13 +1454,14 @@ async def test_delete_company_flattened_async():
# 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_company_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1444,7 +1475,7 @@ def test_list_companies(
transport: str = "grpc", request_type=company_service.ListCompaniesRequest
):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1457,19 +1488,15 @@ def test_list_companies(
call.return_value = company_service.ListCompaniesResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.ListCompaniesRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListCompaniesPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1477,12 +1504,27 @@ def test_list_companies_from_dict():
test_list_companies(request_type=dict)
+def test_list_companies_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompanyServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
+ client.list_companies()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == company_service.ListCompaniesRequest()
+
+
@pytest.mark.asyncio
async def test_list_companies_async(
transport: str = "grpc_asyncio", request_type=company_service.ListCompaniesRequest
):
client = CompanyServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1497,18 +1539,15 @@ async def test_list_companies_async(
next_page_token="next_page_token_value",
)
)
-
response = await client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == company_service.ListCompaniesRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListCompaniesAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1518,17 +1557,17 @@ async def test_list_companies_async_from_dict():
def test_list_companies_field_headers():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.ListCompaniesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
call.return_value = company_service.ListCompaniesResponse()
-
client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
@@ -1543,11 +1582,14 @@ def test_list_companies_field_headers():
@pytest.mark.asyncio
async def test_list_companies_field_headers_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = company_service.ListCompaniesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1555,7 +1597,6 @@ async def test_list_companies_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
company_service.ListCompaniesResponse()
)
-
await client.list_companies(request)
# Establish that the underlying gRPC stub method was called.
@@ -1569,13 +1610,12 @@ async def test_list_companies_field_headers_async():
def test_list_companies_flattened():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = company_service.ListCompaniesResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_companies(parent="parent_value",)
@@ -1584,12 +1624,11 @@ def test_list_companies_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
def test_list_companies_flattened_error():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1601,7 +1640,9 @@ def test_list_companies_flattened_error():
@pytest.mark.asyncio
async def test_list_companies_flattened_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
@@ -1619,13 +1660,14 @@ async def test_list_companies_flattened_async():
# 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_companies_flattened_error_async():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1636,7 +1678,7 @@ async def test_list_companies_flattened_error_async():
def test_list_companies_pager():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
@@ -1670,7 +1712,7 @@ def test_list_companies_pager():
def test_list_companies_pages():
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_companies), "__call__") as call:
@@ -1696,7 +1738,7 @@ def test_list_companies_pages():
@pytest.mark.asyncio
async def test_list_companies_async_pager():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1729,7 +1771,7 @@ async def test_list_companies_async_pager():
@pytest.mark.asyncio
async def test_list_companies_async_pages():
- client = CompanyServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = CompanyServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1760,16 +1802,16 @@ async def test_list_companies_async_pages():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompanyServiceClient(
@@ -1779,7 +1821,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompanyServiceClient(
@@ -1790,7 +1832,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = CompanyServiceClient(transport=transport)
assert client.transport is transport
@@ -1799,13 +1841,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.CompanyServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.CompanyServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -1820,23 +1862,23 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = CompanyServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompanyServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.CompanyServiceGrpcTransport,)
def test_company_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.CompanyServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -1848,7 +1890,7 @@ def test_company_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.CompanyServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -1865,15 +1907,40 @@ def test_company_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_company_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4beta1.services.company_service.transports.CompanyServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.CompanyServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_company_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4beta1.services.company_service.transports.CompanyServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompanyServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -1889,19 +1956,36 @@ def test_company_service_base_transport_with_credentials_file():
def test_company_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4beta1.services.company_service.transports.CompanyServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompanyServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_company_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ CompanyServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_company_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
CompanyServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -1912,14 +1996,44 @@ def test_company_service_auth_adc():
)
-def test_company_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CompanyServiceGrpcTransport,
+ transports.CompanyServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_company_service_transport_auth_adc(transport_class):
# 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.CompanyServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CompanyServiceGrpcTransport,
+ transports.CompanyServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_company_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -1929,9 +2043,92 @@ def test_company_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.CompanyServiceGrpcTransport, grpc_helpers),
+ (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_company_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CompanyServiceGrpcTransport,
+ transports.CompanyServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_company_service_host_no_port():
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -1939,7 +2136,7 @@ def test_company_service_host_no_port():
def test_company_service_host_with_port():
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -1948,7 +2145,7 @@ def test_company_service_host_with_port():
def test_company_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompanyServiceGrpcTransport(
@@ -1960,7 +2157,7 @@ def test_company_service_grpc_transport_channel():
def test_company_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompanyServiceGrpcAsyncIOTransport(
@@ -1971,6 +2168,8 @@ def test_company_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -1985,7 +2184,7 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -1993,9 +2192,9 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -2011,10 +2210,7 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2026,6 +2222,8 @@ def test_company_service_transport_channel_mtls_with_client_cert_source(
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -2041,7 +2239,7 @@ def test_company_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -2059,10 +2257,7 @@ def test_company_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2077,7 +2272,6 @@ def test_company_path():
project = "squid"
tenant = "clam"
company = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -2100,7 +2294,6 @@ def test_parse_company_path():
def test_common_billing_account_path():
billing_account = "cuttlefish"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -2121,7 +2314,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "winkle"
-
expected = "folders/{folder}".format(folder=folder,)
actual = CompanyServiceClient.common_folder_path(folder)
assert expected == actual
@@ -2140,7 +2332,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "scallop"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = CompanyServiceClient.common_organization_path(organization)
assert expected == actual
@@ -2159,7 +2350,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "squid"
-
expected = "projects/{project}".format(project=project,)
actual = CompanyServiceClient.common_project_path(project)
assert expected == actual
@@ -2179,7 +2369,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "whelk"
location = "octopus"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -2206,7 +2395,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.CompanyServiceTransport, "_prep_wrapped_messages"
) as prep:
client = CompanyServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -2215,6 +2404,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = CompanyServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4beta1/test_completion.py b/tests/unit/gapic/talent_v4beta1/test_completion.py
index b03a7da9..aba47d51 100644
--- a/tests/unit/gapic/talent_v4beta1/test_completion.py
+++ b/tests/unit/gapic/talent_v4beta1/test_completion.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,20 +23,38 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4beta1.services.completion import CompletionAsyncClient
from google.cloud.talent_v4beta1.services.completion import CompletionClient
from google.cloud.talent_v4beta1.services.completion import transports
+from google.cloud.talent_v4beta1.services.completion.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import completion_service
from google.oauth2 import service_account
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -81,25 +98,73 @@ def test__get_default_mtls_endpoint():
assert CompletionClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
-@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient])
+@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,])
+def test_completion_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,])
+def test_completion_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.CompletionGrpcTransport, "grpc"),
+ (transports.CompletionGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_completion_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,])
def test_completion_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_completion_client_get_transport_class():
transport = CompletionClient.get_transport_class()
- assert transport == transports.CompletionGrpcTransport
+ available_transports = [
+ transports.CompletionGrpcTransport,
+ ]
+ assert transport in available_transports
transport = CompletionClient.get_transport_class("grpc")
assert transport == transports.CompletionGrpcTransport
@@ -129,7 +194,7 @@ def test_completion_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(CompletionClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -148,7 +213,7 @@ def test_completion_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -164,7 +229,7 @@ def test_completion_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -180,7 +245,7 @@ def test_completion_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -208,7 +273,7 @@ def test_completion_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -257,29 +322,25 @@ def test_completion_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -288,66 +349,53 @@ def test_completion_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -373,7 +421,7 @@ def test_completion_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -403,7 +451,7 @@ def test_completion_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -420,7 +468,7 @@ def test_completion_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -430,7 +478,7 @@ def test_complete_query(
transport: str = "grpc", request_type=completion_service.CompleteQueryRequest
):
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -441,17 +489,14 @@ def test_complete_query(
with mock.patch.object(type(client.transport.complete_query), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = completion_service.CompleteQueryResponse()
-
response = client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == completion_service.CompleteQueryRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, completion_service.CompleteQueryResponse)
@@ -459,13 +504,28 @@ def test_complete_query_from_dict():
test_complete_query(request_type=dict)
+def test_complete_query_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = CompletionClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.complete_query), "__call__") as call:
+ client.complete_query()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == completion_service.CompleteQueryRequest()
+
+
@pytest.mark.asyncio
async def test_complete_query_async(
transport: str = "grpc_asyncio",
request_type=completion_service.CompleteQueryRequest,
):
client = CompletionAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -478,13 +538,11 @@ async def test_complete_query_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
completion_service.CompleteQueryResponse()
)
-
response = await client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == completion_service.CompleteQueryRequest()
# Establish that the response is the type that we expect.
@@ -497,17 +555,17 @@ async def test_complete_query_async_from_dict():
def test_complete_query_field_headers():
- client = CompletionClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompletionClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = completion_service.CompleteQueryRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.complete_query), "__call__") as call:
call.return_value = completion_service.CompleteQueryResponse()
-
client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
@@ -522,11 +580,12 @@ def test_complete_query_field_headers():
@pytest.mark.asyncio
async def test_complete_query_field_headers_async():
- client = CompletionAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompletionAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = completion_service.CompleteQueryRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -534,7 +593,6 @@ async def test_complete_query_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
completion_service.CompleteQueryResponse()
)
-
await client.complete_query(request)
# Establish that the underlying gRPC stub method was called.
@@ -550,16 +608,16 @@ async def test_complete_query_field_headers_async():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompletionClient(
@@ -569,7 +627,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = CompletionClient(
@@ -580,7 +638,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = CompletionClient(transport=transport)
assert client.transport is transport
@@ -589,13 +647,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.CompletionGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.CompletionGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -603,27 +661,27 @@ def test_transport_get_channel():
@pytest.mark.parametrize(
"transport_class",
- [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport,],
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = CompletionClient(credentials=credentials.AnonymousCredentials(),)
+ client = CompletionClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.CompletionGrpcTransport,)
def test_completion_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.CompletionTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -635,7 +693,7 @@ def test_completion_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.CompletionTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -646,15 +704,40 @@ def test_completion_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_completion_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4beta1.services.completion.transports.CompletionTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.CompletionTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_completion_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4beta1.services.completion.transports.CompletionTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompletionTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -670,19 +753,36 @@ def test_completion_base_transport_with_credentials_file():
def test_completion_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4beta1.services.completion.transports.CompletionTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.CompletionTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_completion_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ CompletionClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_completion_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
CompletionClient()
adc.assert_called_once_with(
scopes=(
@@ -693,14 +793,38 @@ def test_completion_auth_adc():
)
-def test_completion_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport,],
+)
+@requires_google_auth_gte_1_25_0
+def test_completion_transport_auth_adc(transport_class):
# 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.CompletionGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport,],
+)
+@requires_google_auth_lt_1_25_0
+def test_completion_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -710,9 +834,89 @@ def test_completion_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.CompletionGrpcTransport, grpc_helpers),
+ (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_completion_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
+)
+def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_completion_host_no_port():
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -720,7 +924,7 @@ def test_completion_host_no_port():
def test_completion_host_with_port():
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -729,7 +933,7 @@ def test_completion_host_with_port():
def test_completion_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompletionGrpcTransport(
@@ -741,7 +945,7 @@ def test_completion_grpc_transport_channel():
def test_completion_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.CompletionGrpcAsyncIOTransport(
@@ -752,6 +956,8 @@ def test_completion_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
@@ -761,7 +967,7 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -769,9 +975,9 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -787,10 +993,7 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -802,6 +1005,8 @@ def test_completion_transport_channel_mtls_with_client_cert_source(transport_cla
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport],
@@ -814,7 +1019,7 @@ def test_completion_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -832,10 +1037,7 @@ def test_completion_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -850,7 +1052,6 @@ def test_company_path():
project = "squid"
tenant = "clam"
company = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -873,7 +1074,6 @@ def test_parse_company_path():
def test_common_billing_account_path():
billing_account = "cuttlefish"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -894,7 +1094,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "winkle"
-
expected = "folders/{folder}".format(folder=folder,)
actual = CompletionClient.common_folder_path(folder)
assert expected == actual
@@ -913,7 +1112,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "scallop"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = CompletionClient.common_organization_path(organization)
assert expected == actual
@@ -932,7 +1130,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "squid"
-
expected = "projects/{project}".format(project=project,)
actual = CompletionClient.common_project_path(project)
assert expected == actual
@@ -952,7 +1149,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "whelk"
location = "octopus"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -979,7 +1175,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.CompletionTransport, "_prep_wrapped_messages"
) as prep:
client = CompletionClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -988,6 +1184,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = CompletionClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4beta1/test_event_service.py b/tests/unit/gapic/talent_v4beta1/test_event_service.py
index a5f2b7c0..ecfff6a4 100644
--- a/tests/unit/gapic/talent_v4beta1/test_event_service.py
+++ b/tests/unit/gapic/talent_v4beta1/test_event_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,21 +23,39 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4beta1.services.event_service import EventServiceAsyncClient
from google.cloud.talent_v4beta1.services.event_service import EventServiceClient
from google.cloud.talent_v4beta1.services.event_service import transports
+from google.cloud.talent_v4beta1.services.event_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4beta1.types import event
from google.cloud.talent_v4beta1.types import event_service
from google.oauth2 import service_account
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -82,25 +99,73 @@ def test__get_default_mtls_endpoint():
assert EventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
-@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient])
+@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,])
+def test_event_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,])
+def test_event_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.EventServiceGrpcTransport, "grpc"),
+ (transports.EventServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_event_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,])
def test_event_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_event_service_client_get_transport_class():
transport = EventServiceClient.get_transport_class()
- assert transport == transports.EventServiceGrpcTransport
+ available_transports = [
+ transports.EventServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = EventServiceClient.get_transport_class("grpc")
assert transport == transports.EventServiceGrpcTransport
@@ -130,7 +195,7 @@ def test_event_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(EventServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -149,7 +214,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -165,7 +230,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -181,7 +246,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -209,7 +274,7 @@ def test_event_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -258,29 +323,25 @@ def test_event_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -289,66 +350,53 @@ def test_event_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -374,7 +422,7 @@ def test_event_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -404,7 +452,7 @@ def test_event_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -421,7 +469,7 @@ def test_event_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -431,7 +479,7 @@ def test_create_client_event(
transport: str = "grpc", request_type=event_service.CreateClientEventRequest
):
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -449,23 +497,17 @@ def test_create_client_event(
event_notes="event_notes_value",
job_event=event.JobEvent(type_=event.JobEvent.JobEventType.IMPRESSION),
)
-
response = client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == event_service.CreateClientEventRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, event.ClientEvent)
-
assert response.request_id == "request_id_value"
-
assert response.event_id == "event_id_value"
-
assert response.event_notes == "event_notes_value"
@@ -473,12 +515,29 @@ def test_create_client_event_from_dict():
test_create_client_event(request_type=dict)
+def test_create_client_event_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = EventServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_client_event), "__call__"
+ ) as call:
+ client.create_client_event()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == event_service.CreateClientEventRequest()
+
+
@pytest.mark.asyncio
async def test_create_client_event_async(
transport: str = "grpc_asyncio", request_type=event_service.CreateClientEventRequest
):
client = EventServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -497,22 +556,17 @@ async def test_create_client_event_async(
event_notes="event_notes_value",
)
)
-
response = await client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == event_service.CreateClientEventRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, event.ClientEvent)
-
assert response.request_id == "request_id_value"
-
assert response.event_id == "event_id_value"
-
assert response.event_notes == "event_notes_value"
@@ -522,11 +576,12 @@ async def test_create_client_event_async_from_dict():
def test_create_client_event_field_headers():
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = event_service.CreateClientEventRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -534,7 +589,6 @@ def test_create_client_event_field_headers():
type(client.transport.create_client_event), "__call__"
) as call:
call.return_value = event.ClientEvent()
-
client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
@@ -549,11 +603,12 @@ def test_create_client_event_field_headers():
@pytest.mark.asyncio
async def test_create_client_event_field_headers_async():
- client = EventServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = event_service.CreateClientEventRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -561,7 +616,6 @@ async def test_create_client_event_field_headers_async():
type(client.transport.create_client_event), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event.ClientEvent())
-
await client.create_client_event(request)
# Establish that the underlying gRPC stub method was called.
@@ -575,7 +629,7 @@ async def test_create_client_event_field_headers_async():
def test_create_client_event_flattened():
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -583,7 +637,6 @@ def test_create_client_event_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = event.ClientEvent()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_client_event(
@@ -595,14 +648,12 @@ def test_create_client_event_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].client_event == event.ClientEvent(request_id="request_id_value")
def test_create_client_event_flattened_error():
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -616,7 +667,7 @@ def test_create_client_event_flattened_error():
@pytest.mark.asyncio
async def test_create_client_event_flattened_async():
- client = EventServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -637,15 +688,13 @@ async def test_create_client_event_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].client_event == event.ClientEvent(request_id="request_id_value")
@pytest.mark.asyncio
async def test_create_client_event_flattened_error_async():
- client = EventServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -660,16 +709,16 @@ async def test_create_client_event_flattened_error_async():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = EventServiceClient(
@@ -679,7 +728,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = EventServiceClient(
@@ -690,7 +739,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = EventServiceClient(transport=transport)
assert client.transport is transport
@@ -699,13 +748,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.EventServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.EventServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -713,27 +762,30 @@ def test_transport_get_channel():
@pytest.mark.parametrize(
"transport_class",
- [transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
+ [
+ transports.EventServiceGrpcTransport,
+ transports.EventServiceGrpcAsyncIOTransport,
+ ],
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = EventServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = EventServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.EventServiceGrpcTransport,)
def test_event_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.EventServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -745,7 +797,7 @@ def test_event_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.EventServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -756,15 +808,40 @@ def test_event_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_event_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4beta1.services.event_service.transports.EventServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.EventServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_event_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4beta1.services.event_service.transports.EventServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.EventServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -780,19 +857,36 @@ def test_event_service_base_transport_with_credentials_file():
def test_event_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4beta1.services.event_service.transports.EventServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.EventServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_event_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ EventServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_event_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
EventServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -803,14 +897,44 @@ def test_event_service_auth_adc():
)
-def test_event_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.EventServiceGrpcTransport,
+ transports.EventServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_event_service_transport_auth_adc(transport_class):
# 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.EventServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.EventServiceGrpcTransport,
+ transports.EventServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_event_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -820,9 +944,89 @@ def test_event_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.EventServiceGrpcTransport, grpc_helpers),
+ (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_event_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
+)
+def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_event_service_host_no_port():
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -830,7 +1034,7 @@ def test_event_service_host_no_port():
def test_event_service_host_with_port():
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -839,7 +1043,7 @@ def test_event_service_host_with_port():
def test_event_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.EventServiceGrpcTransport(
@@ -851,7 +1055,7 @@ def test_event_service_grpc_transport_channel():
def test_event_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.EventServiceGrpcAsyncIOTransport(
@@ -862,6 +1066,8 @@ def test_event_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
@@ -871,7 +1077,7 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -879,9 +1085,9 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -897,10 +1103,7 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -912,6 +1115,8 @@ def test_event_service_transport_channel_mtls_with_client_cert_source(transport_
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport],
@@ -924,7 +1129,7 @@ def test_event_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -942,10 +1147,7 @@ def test_event_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -960,7 +1162,6 @@ def test_company_path():
project = "squid"
tenant = "clam"
company = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -983,7 +1184,6 @@ def test_parse_company_path():
def test_common_billing_account_path():
billing_account = "cuttlefish"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -1004,7 +1204,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "winkle"
-
expected = "folders/{folder}".format(folder=folder,)
actual = EventServiceClient.common_folder_path(folder)
assert expected == actual
@@ -1023,7 +1222,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "scallop"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = EventServiceClient.common_organization_path(organization)
assert expected == actual
@@ -1042,7 +1240,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "squid"
-
expected = "projects/{project}".format(project=project,)
actual = EventServiceClient.common_project_path(project)
assert expected == actual
@@ -1062,7 +1259,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "whelk"
location = "octopus"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -1089,7 +1285,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.EventServiceTransport, "_prep_wrapped_messages"
) as prep:
client = EventServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -1098,6 +1294,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = EventServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4beta1/test_job_service.py b/tests/unit/gapic/talent_v4beta1/test_job_service.py
index 43896c99..8f9a3e8e 100644
--- a/tests/unit/gapic/talent_v4beta1/test_job_service.py
+++ b/tests/unit/gapic/talent_v4beta1/test_job_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,21 +23,24 @@
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 exceptions as core_exceptions
from google.api_core import future
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.api_core import operation_async # type: ignore
from google.api_core import operations_v1
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4beta1.services.job_service import JobServiceAsyncClient
from google.cloud.talent_v4beta1.services.job_service import JobServiceClient
from google.cloud.talent_v4beta1.services.job_service import pagers
from google.cloud.talent_v4beta1.services.job_service import transports
+from google.cloud.talent_v4beta1.services.job_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import filters
from google.cloud.talent_v4beta1.types import histogram
@@ -47,14 +49,29 @@
from google.cloud.talent_v4beta1.types import job_service
from google.longrunning import operations_pb2
from google.oauth2 import service_account
-from google.protobuf import duration_pb2 as duration # type: ignore
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
-from google.protobuf import timestamp_pb2 as timestamp # type: ignore
-from google.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import money_pb2 as money # type: ignore
-from google.type import postal_address_pb2 as postal_address # type: ignore
-from google.type import timeofday_pb2 as timeofday # type: ignore
+from google.protobuf import duration_pb2 # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import money_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
+from google.type import timeofday_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -98,25 +115,73 @@ def test__get_default_mtls_endpoint():
assert JobServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
-@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient])
+@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,])
+def test_job_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,])
+def test_job_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.JobServiceGrpcTransport, "grpc"),
+ (transports.JobServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_job_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,])
def test_job_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_job_service_client_get_transport_class():
transport = JobServiceClient.get_transport_class()
- assert transport == transports.JobServiceGrpcTransport
+ available_transports = [
+ transports.JobServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = JobServiceClient.get_transport_class("grpc")
assert transport == transports.JobServiceGrpcTransport
@@ -146,7 +211,7 @@ def test_job_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(JobServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -165,7 +230,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -181,7 +246,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -197,7 +262,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -225,7 +290,7 @@ def test_job_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -274,29 +339,25 @@ def test_job_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -305,66 +366,53 @@ def test_job_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -390,7 +438,7 @@ def test_job_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -420,7 +468,7 @@ def test_job_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -437,7 +485,7 @@ def test_job_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -445,7 +493,7 @@ def test_job_service_client_client_options_from_dict():
def test_create_job(transport: str = "grpc", request_type=job_service.CreateJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -476,55 +524,33 @@ def test_create_job(transport: str = "grpc", request_type=job_service.CreateJobR
visibility=common.Visibility.ACCOUNT_ONLY,
company_display_name="company_display_name_value",
)
-
response = client.create_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.CreateJobRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -532,12 +558,27 @@ def test_create_job_from_dict():
test_create_job(request_type=dict)
+def test_create_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_job), "__call__") as call:
+ client.create_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.CreateJobRequest()
+
+
@pytest.mark.asyncio
async def test_create_job_async(
transport: str = "grpc_asyncio", request_type=job_service.CreateJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -570,54 +611,33 @@ async def test_create_job_async(
company_display_name="company_display_name_value",
)
)
-
response = await client.create_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.CreateJobRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -627,17 +647,17 @@ async def test_create_job_async_from_dict():
def test_create_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.CreateJobRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
call.return_value = gct_job.Job()
-
client.create_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -652,17 +672,17 @@ def test_create_job_field_headers():
@pytest.mark.asyncio
async def test_create_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.CreateJobRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_job.Job())
-
await client.create_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -676,13 +696,12 @@ async def test_create_job_field_headers_async():
def test_create_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_job.Job()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_job(
@@ -693,14 +712,12 @@ def test_create_job_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].job == gct_job.Job(name="name_value")
def test_create_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -714,7 +731,7 @@ def test_create_job_flattened_error():
@pytest.mark.asyncio
async def test_create_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_job), "__call__") as call:
@@ -732,15 +749,13 @@ async def test_create_job_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].job == gct_job.Job(name="name_value")
@pytest.mark.asyncio
async def test_create_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -756,7 +771,7 @@ def test_batch_create_jobs(
transport: str = "grpc", request_type=job_service.BatchCreateJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -769,13 +784,11 @@ def test_batch_create_jobs(
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/spam")
-
response = client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchCreateJobsRequest()
# Establish that the response is the type that we expect.
@@ -786,12 +799,29 @@ def test_batch_create_jobs_from_dict():
test_batch_create_jobs(request_type=dict)
+def test_batch_create_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_create_jobs), "__call__"
+ ) as call:
+ client.batch_create_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.BatchCreateJobsRequest()
+
+
@pytest.mark.asyncio
async def test_batch_create_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.BatchCreateJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -806,13 +836,11 @@ async def test_batch_create_jobs_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/spam")
)
-
response = await client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchCreateJobsRequest()
# Establish that the response is the type that we expect.
@@ -825,11 +853,12 @@ async def test_batch_create_jobs_async_from_dict():
def test_batch_create_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchCreateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -837,7 +866,6 @@ def test_batch_create_jobs_field_headers():
type(client.transport.batch_create_jobs), "__call__"
) as call:
call.return_value = operations_pb2.Operation(name="operations/op")
-
client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -852,11 +880,12 @@ def test_batch_create_jobs_field_headers():
@pytest.mark.asyncio
async def test_batch_create_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchCreateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -866,7 +895,6 @@ async def test_batch_create_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/op")
)
-
await client.batch_create_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -880,7 +908,7 @@ async def test_batch_create_jobs_field_headers_async():
def test_batch_create_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -888,7 +916,6 @@ def test_batch_create_jobs_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/op")
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.batch_create_jobs(
@@ -899,14 +926,12 @@ def test_batch_create_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
def test_batch_create_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -920,7 +945,7 @@ def test_batch_create_jobs_flattened_error():
@pytest.mark.asyncio
async def test_batch_create_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -942,15 +967,13 @@ async def test_batch_create_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
@pytest.mark.asyncio
async def test_batch_create_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -964,7 +987,7 @@ async def test_batch_create_jobs_flattened_error_async():
def test_get_job(transport: str = "grpc", request_type=job_service.GetJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -995,55 +1018,33 @@ def test_get_job(transport: str = "grpc", request_type=job_service.GetJobRequest
visibility=common.Visibility.ACCOUNT_ONLY,
company_display_name="company_display_name_value",
)
-
response = client.get_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.GetJobRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1051,12 +1052,27 @@ def test_get_job_from_dict():
test_get_job(request_type=dict)
+def test_get_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_job), "__call__") as call:
+ client.get_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.GetJobRequest()
+
+
@pytest.mark.asyncio
async def test_get_job_async(
transport: str = "grpc_asyncio", request_type=job_service.GetJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1089,54 +1105,33 @@ async def test_get_job_async(
company_display_name="company_display_name_value",
)
)
-
response = await client.get_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.GetJobRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1146,17 +1141,17 @@ async def test_get_job_async_from_dict():
def test_get_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.GetJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
call.return_value = job.Job()
-
client.get_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1171,17 +1166,17 @@ def test_get_job_field_headers():
@pytest.mark.asyncio
async def test_get_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.GetJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(job.Job())
-
await client.get_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1195,13 +1190,12 @@ async def test_get_job_field_headers_async():
def test_get_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = job.Job()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_job(name="name_value",)
@@ -1210,12 +1204,11 @@ def test_get_job_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1227,7 +1220,7 @@ def test_get_job_flattened_error():
@pytest.mark.asyncio
async def test_get_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_job), "__call__") as call:
@@ -1243,13 +1236,12 @@ async def test_get_job_flattened_async():
# 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_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1261,7 +1253,7 @@ async def test_get_job_flattened_error_async():
def test_update_job(transport: str = "grpc", request_type=job_service.UpdateJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1292,55 +1284,33 @@ def test_update_job(transport: str = "grpc", request_type=job_service.UpdateJobR
visibility=common.Visibility.ACCOUNT_ONLY,
company_display_name="company_display_name_value",
)
-
response = client.update_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.UpdateJobRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1348,12 +1318,27 @@ def test_update_job_from_dict():
test_update_job(request_type=dict)
+def test_update_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_job), "__call__") as call:
+ client.update_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.UpdateJobRequest()
+
+
@pytest.mark.asyncio
async def test_update_job_async(
transport: str = "grpc_asyncio", request_type=job_service.UpdateJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1386,54 +1371,33 @@ async def test_update_job_async(
company_display_name="company_display_name_value",
)
)
-
response = await client.update_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.UpdateJobRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_job.Job)
-
assert response.name == "name_value"
-
assert response.company == "company_value"
-
assert response.requisition_id == "requisition_id_value"
-
assert response.title == "title_value"
-
assert response.description == "description_value"
-
assert response.addresses == ["addresses_value"]
-
assert response.job_benefits == [common.JobBenefit.CHILD_CARE]
-
assert response.degree_types == [common.DegreeType.PRIMARY_EDUCATION]
-
assert response.department == "department_value"
-
assert response.employment_types == [common.EmploymentType.FULL_TIME]
-
assert response.incentives == "incentives_value"
-
assert response.language_code == "language_code_value"
-
assert response.job_level == common.JobLevel.ENTRY_LEVEL
-
assert response.promotion_value == 1635
-
assert response.qualifications == "qualifications_value"
-
assert response.responsibilities == "responsibilities_value"
-
assert response.posting_region == common.PostingRegion.ADMINISTRATIVE_AREA
-
assert response.visibility == common.Visibility.ACCOUNT_ONLY
-
assert response.company_display_name == "company_display_name_value"
@@ -1443,17 +1407,17 @@ async def test_update_job_async_from_dict():
def test_update_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.UpdateJobRequest()
+
request.job.name = "job.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
call.return_value = gct_job.Job()
-
client.update_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1468,17 +1432,17 @@ def test_update_job_field_headers():
@pytest.mark.asyncio
async def test_update_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.UpdateJobRequest()
+
request.job.name = "job.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_job.Job())
-
await client.update_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1492,13 +1456,12 @@ async def test_update_job_field_headers_async():
def test_update_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_job.Job()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_job(job=gct_job.Job(name="name_value"),)
@@ -1507,12 +1470,11 @@ def test_update_job_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].job == gct_job.Job(name="name_value")
def test_update_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1524,7 +1486,7 @@ def test_update_job_flattened_error():
@pytest.mark.asyncio
async def test_update_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_job), "__call__") as call:
@@ -1540,13 +1502,12 @@ async def test_update_job_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].job == gct_job.Job(name="name_value")
@pytest.mark.asyncio
async def test_update_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1560,7 +1521,7 @@ def test_batch_update_jobs(
transport: str = "grpc", request_type=job_service.BatchUpdateJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1573,13 +1534,11 @@ def test_batch_update_jobs(
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/spam")
-
response = client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchUpdateJobsRequest()
# Establish that the response is the type that we expect.
@@ -1590,12 +1549,29 @@ def test_batch_update_jobs_from_dict():
test_batch_update_jobs(request_type=dict)
+def test_batch_update_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_jobs), "__call__"
+ ) as call:
+ client.batch_update_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.BatchUpdateJobsRequest()
+
+
@pytest.mark.asyncio
async def test_batch_update_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.BatchUpdateJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1610,13 +1586,11 @@ async def test_batch_update_jobs_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/spam")
)
-
response = await client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchUpdateJobsRequest()
# Establish that the response is the type that we expect.
@@ -1629,11 +1603,12 @@ async def test_batch_update_jobs_async_from_dict():
def test_batch_update_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchUpdateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1641,7 +1616,6 @@ def test_batch_update_jobs_field_headers():
type(client.transport.batch_update_jobs), "__call__"
) as call:
call.return_value = operations_pb2.Operation(name="operations/op")
-
client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -1656,11 +1630,12 @@ def test_batch_update_jobs_field_headers():
@pytest.mark.asyncio
async def test_batch_update_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchUpdateJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1670,7 +1645,6 @@ async def test_batch_update_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
operations_pb2.Operation(name="operations/op")
)
-
await client.batch_update_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -1684,7 +1658,7 @@ async def test_batch_update_jobs_field_headers_async():
def test_batch_update_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1692,7 +1666,6 @@ def test_batch_update_jobs_flattened():
) as call:
# Designate an appropriate return value for the call.
call.return_value = operations_pb2.Operation(name="operations/op")
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.batch_update_jobs(
@@ -1703,14 +1676,12 @@ def test_batch_update_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
def test_batch_update_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1724,7 +1695,7 @@ def test_batch_update_jobs_flattened_error():
@pytest.mark.asyncio
async def test_batch_update_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1746,15 +1717,13 @@ async def test_batch_update_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].jobs == [job.Job(name="name_value")]
@pytest.mark.asyncio
async def test_batch_update_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1768,7 +1737,7 @@ async def test_batch_update_jobs_flattened_error_async():
def test_delete_job(transport: str = "grpc", request_type=job_service.DeleteJobRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1779,13 +1748,11 @@ def test_delete_job(transport: str = "grpc", request_type=job_service.DeleteJobR
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.DeleteJobRequest()
# Establish that the response is the type that we expect.
@@ -1796,12 +1763,27 @@ def test_delete_job_from_dict():
test_delete_job(request_type=dict)
+def test_delete_job_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
+ client.delete_job()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.DeleteJobRequest()
+
+
@pytest.mark.asyncio
async def test_delete_job_async(
transport: str = "grpc_asyncio", request_type=job_service.DeleteJobRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1812,13 +1794,11 @@ async def test_delete_job_async(
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.DeleteJobRequest()
# Establish that the response is the type that we expect.
@@ -1831,17 +1811,17 @@ async def test_delete_job_async_from_dict():
def test_delete_job_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.DeleteJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
call.return_value = None
-
client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1856,17 +1836,17 @@ def test_delete_job_field_headers():
@pytest.mark.asyncio
async def test_delete_job_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.DeleteJobRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_job(request)
# Establish that the underlying gRPC stub method was called.
@@ -1880,13 +1860,12 @@ async def test_delete_job_field_headers_async():
def test_delete_job_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__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_job(name="name_value",)
@@ -1895,12 +1874,11 @@ def test_delete_job_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_job_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1912,7 +1890,7 @@ def test_delete_job_flattened_error():
@pytest.mark.asyncio
async def test_delete_job_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_job), "__call__") as call:
@@ -1928,13 +1906,12 @@ async def test_delete_job_flattened_async():
# 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_job_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1948,7 +1925,7 @@ def test_batch_delete_jobs(
transport: str = "grpc", request_type=job_service.BatchDeleteJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1961,13 +1938,11 @@ def test_batch_delete_jobs(
) as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchDeleteJobsRequest()
# Establish that the response is the type that we expect.
@@ -1978,12 +1953,29 @@ def test_batch_delete_jobs_from_dict():
test_batch_delete_jobs(request_type=dict)
+def test_batch_delete_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_delete_jobs), "__call__"
+ ) as call:
+ client.batch_delete_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.BatchDeleteJobsRequest()
+
+
@pytest.mark.asyncio
async def test_batch_delete_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.BatchDeleteJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1996,13 +1988,11 @@ async def test_batch_delete_jobs_async(
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.BatchDeleteJobsRequest()
# Establish that the response is the type that we expect.
@@ -2015,11 +2005,12 @@ async def test_batch_delete_jobs_async_from_dict():
def test_batch_delete_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchDeleteJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2027,7 +2018,6 @@ def test_batch_delete_jobs_field_headers():
type(client.transport.batch_delete_jobs), "__call__"
) as call:
call.return_value = None
-
client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2042,11 +2032,12 @@ def test_batch_delete_jobs_field_headers():
@pytest.mark.asyncio
async def test_batch_delete_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.BatchDeleteJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2054,7 +2045,6 @@ async def test_batch_delete_jobs_field_headers_async():
type(client.transport.batch_delete_jobs), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.batch_delete_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2068,7 +2058,7 @@ async def test_batch_delete_jobs_field_headers_async():
def test_batch_delete_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2076,7 +2066,6 @@ def test_batch_delete_jobs_flattened():
) 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.batch_delete_jobs(
@@ -2087,14 +2076,12 @@ def test_batch_delete_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].filter == "filter_value"
def test_batch_delete_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2108,7 +2095,7 @@ def test_batch_delete_jobs_flattened_error():
@pytest.mark.asyncio
async def test_batch_delete_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2128,15 +2115,13 @@ async def test_batch_delete_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].filter == "filter_value"
@pytest.mark.asyncio
async def test_batch_delete_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2150,7 +2135,7 @@ async def test_batch_delete_jobs_flattened_error_async():
def test_list_jobs(transport: str = "grpc", request_type=job_service.ListJobsRequest):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2163,19 +2148,15 @@ def test_list_jobs(transport: str = "grpc", request_type=job_service.ListJobsReq
call.return_value = job_service.ListJobsResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.ListJobsRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListJobsPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -2183,12 +2164,27 @@ def test_list_jobs_from_dict():
test_list_jobs(request_type=dict)
+def test_list_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
+ client.list_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.ListJobsRequest()
+
+
@pytest.mark.asyncio
async def test_list_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.ListJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2201,18 +2197,15 @@ async def test_list_jobs_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.ListJobsResponse(next_page_token="next_page_token_value",)
)
-
response = await client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.ListJobsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListJobsAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -2222,17 +2215,17 @@ async def test_list_jobs_async_from_dict():
def test_list_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.ListJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
call.return_value = job_service.ListJobsResponse()
-
client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2247,11 +2240,12 @@ def test_list_jobs_field_headers():
@pytest.mark.asyncio
async def test_list_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.ListJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2259,7 +2253,6 @@ async def test_list_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.ListJobsResponse()
)
-
await client.list_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2273,13 +2266,12 @@ async def test_list_jobs_field_headers_async():
def test_list_jobs_flattened():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = job_service.ListJobsResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_jobs(
@@ -2290,14 +2282,12 @@ def test_list_jobs_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].filter == "filter_value"
def test_list_jobs_flattened_error():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2309,7 +2299,7 @@ def test_list_jobs_flattened_error():
@pytest.mark.asyncio
async def test_list_jobs_flattened_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
@@ -2327,15 +2317,13 @@ async def test_list_jobs_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].filter == "filter_value"
@pytest.mark.asyncio
async def test_list_jobs_flattened_error_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -2346,7 +2334,7 @@ async def test_list_jobs_flattened_error_async():
def test_list_jobs_pager():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
@@ -2375,7 +2363,7 @@ def test_list_jobs_pager():
def test_list_jobs_pages():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_jobs), "__call__") as call:
@@ -2396,7 +2384,7 @@ def test_list_jobs_pages():
@pytest.mark.asyncio
async def test_list_jobs_async_pager():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2424,7 +2412,7 @@ async def test_list_jobs_async_pager():
@pytest.mark.asyncio
async def test_list_jobs_async_pages():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2451,7 +2439,7 @@ def test_search_jobs(
transport: str = "grpc", request_type=job_service.SearchJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2467,25 +2455,18 @@ def test_search_jobs(
total_size=1086,
broadened_query_jobs_count=2766,
)
-
response = client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.SearchJobsPager)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.estimated_total_size == 2141
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2493,12 +2474,27 @@ def test_search_jobs_from_dict():
test_search_jobs(request_type=dict)
+def test_search_jobs_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.search_jobs), "__call__") as call:
+ client.search_jobs()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.SearchJobsRequest()
+
+
@pytest.mark.asyncio
async def test_search_jobs_async(
transport: str = "grpc_asyncio", request_type=job_service.SearchJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2516,24 +2512,18 @@ async def test_search_jobs_async(
broadened_query_jobs_count=2766,
)
)
-
response = await client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.SearchJobsAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.estimated_total_size == 2141
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2543,17 +2533,17 @@ async def test_search_jobs_async_from_dict():
def test_search_jobs_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.search_jobs), "__call__") as call:
call.return_value = job_service.SearchJobsResponse()
-
client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2568,11 +2558,12 @@ def test_search_jobs_field_headers():
@pytest.mark.asyncio
async def test_search_jobs_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2580,7 +2571,6 @@ async def test_search_jobs_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.SearchJobsResponse()
)
-
await client.search_jobs(request)
# Establish that the underlying gRPC stub method was called.
@@ -2594,7 +2584,7 @@ async def test_search_jobs_field_headers_async():
def test_search_jobs_pager():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.search_jobs), "__call__") as call:
@@ -2638,7 +2628,7 @@ def test_search_jobs_pager():
def test_search_jobs_pages():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.search_jobs), "__call__") as call:
@@ -2672,7 +2662,7 @@ def test_search_jobs_pages():
@pytest.mark.asyncio
async def test_search_jobs_async_pager():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2715,7 +2705,7 @@ async def test_search_jobs_async_pager():
@pytest.mark.asyncio
async def test_search_jobs_async_pages():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2755,7 +2745,7 @@ def test_search_jobs_for_alert(
transport: str = "grpc", request_type=job_service.SearchJobsRequest
):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2773,25 +2763,18 @@ def test_search_jobs_for_alert(
total_size=1086,
broadened_query_jobs_count=2766,
)
-
response = client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.SearchJobsForAlertPager)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.estimated_total_size == 2141
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2799,12 +2782,29 @@ def test_search_jobs_for_alert_from_dict():
test_search_jobs_for_alert(request_type=dict)
+def test_search_jobs_for_alert_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = JobServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.search_jobs_for_alert), "__call__"
+ ) as call:
+ client.search_jobs_for_alert()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == job_service.SearchJobsRequest()
+
+
@pytest.mark.asyncio
async def test_search_jobs_for_alert_async(
transport: str = "grpc_asyncio", request_type=job_service.SearchJobsRequest
):
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -2824,24 +2824,18 @@ async def test_search_jobs_for_alert_async(
broadened_query_jobs_count=2766,
)
)
-
response = await client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == job_service.SearchJobsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.SearchJobsForAlertAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
-
assert response.estimated_total_size == 2141
-
assert response.total_size == 1086
-
assert response.broadened_query_jobs_count == 2766
@@ -2851,11 +2845,12 @@ async def test_search_jobs_for_alert_async_from_dict():
def test_search_jobs_for_alert_field_headers():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2863,7 +2858,6 @@ def test_search_jobs_for_alert_field_headers():
type(client.transport.search_jobs_for_alert), "__call__"
) as call:
call.return_value = job_service.SearchJobsResponse()
-
client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
@@ -2878,11 +2872,12 @@ def test_search_jobs_for_alert_field_headers():
@pytest.mark.asyncio
async def test_search_jobs_for_alert_field_headers_async():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = job_service.SearchJobsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -2892,7 +2887,6 @@ async def test_search_jobs_for_alert_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
job_service.SearchJobsResponse()
)
-
await client.search_jobs_for_alert(request)
# Establish that the underlying gRPC stub method was called.
@@ -2906,7 +2900,7 @@ async def test_search_jobs_for_alert_field_headers_async():
def test_search_jobs_for_alert_pager():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2952,7 +2946,7 @@ def test_search_jobs_for_alert_pager():
def test_search_jobs_for_alert_pages():
- client = JobServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -2988,7 +2982,7 @@ def test_search_jobs_for_alert_pages():
@pytest.mark.asyncio
async def test_search_jobs_for_alert_async_pager():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -3033,7 +3027,7 @@ async def test_search_jobs_for_alert_async_pager():
@pytest.mark.asyncio
async def test_search_jobs_for_alert_async_pages():
- client = JobServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = JobServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -3074,16 +3068,16 @@ async def test_search_jobs_for_alert_async_pages():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = JobServiceClient(
@@ -3093,7 +3087,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = JobServiceClient(
@@ -3104,7 +3098,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = JobServiceClient(transport=transport)
assert client.transport is transport
@@ -3113,13 +3107,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.JobServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.JobServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -3127,27 +3121,27 @@ def test_transport_get_channel():
@pytest.mark.parametrize(
"transport_class",
- [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport,],
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = JobServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = JobServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.JobServiceGrpcTransport,)
def test_job_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.JobServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -3159,7 +3153,7 @@ def test_job_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.JobServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -3186,15 +3180,40 @@ def test_job_service_base_transport():
transport.operations_client
+@requires_google_auth_gte_1_25_0
def test_job_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4beta1.services.job_service.transports.JobServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.JobServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_job_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4beta1.services.job_service.transports.JobServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.JobServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -3210,19 +3229,36 @@ def test_job_service_base_transport_with_credentials_file():
def test_job_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4beta1.services.job_service.transports.JobServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.JobServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_job_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ JobServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_job_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
JobServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -3233,14 +3269,38 @@ def test_job_service_auth_adc():
)
-def test_job_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport,],
+)
+@requires_google_auth_gte_1_25_0
+def test_job_service_transport_auth_adc(transport_class):
# 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.JobServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport,],
+)
+@requires_google_auth_lt_1_25_0
+def test_job_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -3250,9 +3310,89 @@ def test_job_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.JobServiceGrpcTransport, grpc_helpers),
+ (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_job_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
+)
+def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_job_service_host_no_port():
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -3260,7 +3400,7 @@ def test_job_service_host_no_port():
def test_job_service_host_with_port():
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -3269,7 +3409,7 @@ def test_job_service_host_with_port():
def test_job_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.JobServiceGrpcTransport(
@@ -3281,7 +3421,7 @@ def test_job_service_grpc_transport_channel():
def test_job_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.JobServiceGrpcAsyncIOTransport(
@@ -3292,6 +3432,8 @@ def test_job_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
@@ -3301,7 +3443,7 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -3309,9 +3451,9 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -3327,10 +3469,7 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -3342,6 +3481,8 @@ def test_job_service_transport_channel_mtls_with_client_cert_source(transport_cl
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport],
@@ -3354,7 +3495,7 @@ def test_job_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -3372,10 +3513,7 @@ def test_job_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -3388,7 +3526,7 @@ def test_job_service_transport_channel_mtls_with_adc(transport_class):
def test_job_service_grpc_lro_client():
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc",
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
)
transport = client.transport
@@ -3401,7 +3539,7 @@ def test_job_service_grpc_lro_client():
def test_job_service_grpc_lro_async_client():
client = JobServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio",
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio",
)
transport = client.transport
@@ -3416,7 +3554,6 @@ def test_company_path():
project = "squid"
tenant = "clam"
company = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/companies/{company}".format(
project=project, tenant=tenant, company=company,
)
@@ -3441,7 +3578,6 @@ def test_job_path():
project = "cuttlefish"
tenant = "mussel"
job = "winkle"
-
expected = "projects/{project}/tenants/{tenant}/jobs/{job}".format(
project=project, tenant=tenant, job=job,
)
@@ -3464,7 +3600,6 @@ def test_parse_job_path():
def test_common_billing_account_path():
billing_account = "squid"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -3485,7 +3620,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "whelk"
-
expected = "folders/{folder}".format(folder=folder,)
actual = JobServiceClient.common_folder_path(folder)
assert expected == actual
@@ -3504,7 +3638,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "oyster"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = JobServiceClient.common_organization_path(organization)
assert expected == actual
@@ -3523,7 +3656,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "cuttlefish"
-
expected = "projects/{project}".format(project=project,)
actual = JobServiceClient.common_project_path(project)
assert expected == actual
@@ -3543,7 +3675,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "winkle"
location = "nautilus"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -3570,7 +3701,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.JobServiceTransport, "_prep_wrapped_messages"
) as prep:
client = JobServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -3579,6 +3710,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = JobServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4beta1/test_profile_service.py b/tests/unit/gapic/talent_v4beta1/test_profile_service.py
index 136e0be1..0d8f84c7 100644
--- a/tests/unit/gapic/talent_v4beta1/test_profile_service.py
+++ b/tests/unit/gapic/talent_v4beta1/test_profile_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,13 +23,13 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4beta1.services.profile_service import (
ProfileServiceAsyncClient,
@@ -38,6 +37,9 @@
from google.cloud.talent_v4beta1.services.profile_service import ProfileServiceClient
from google.cloud.talent_v4beta1.services.profile_service import pagers
from google.cloud.talent_v4beta1.services.profile_service import transports
+from google.cloud.talent_v4beta1.services.profile_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4beta1.types import common
from google.cloud.talent_v4beta1.types import filters
from google.cloud.talent_v4beta1.types import histogram
@@ -45,13 +47,28 @@
from google.cloud.talent_v4beta1.types import profile as gct_profile
from google.cloud.talent_v4beta1.types import profile_service
from google.oauth2 import service_account
-from google.protobuf import duration_pb2 as duration # 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.protobuf import wrappers_pb2 as wrappers # type: ignore
-from google.type import date_pb2 as date # type: ignore
-from google.type import latlng_pb2 as latlng # type: ignore
-from google.type import postal_address_pb2 as postal_address # type: ignore
+from google.protobuf import duration_pb2 # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+from google.protobuf import timestamp_pb2 # type: ignore
+from google.protobuf import wrappers_pb2 # type: ignore
+from google.type import date_pb2 # type: ignore
+from google.type import latlng_pb2 # type: ignore
+from google.type import postal_address_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -99,26 +116,78 @@ def test__get_default_mtls_endpoint():
@pytest.mark.parametrize(
- "client_class", [ProfileServiceClient, ProfileServiceAsyncClient]
+ "client_class", [ProfileServiceClient, ProfileServiceAsyncClient,]
+)
+def test_profile_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [ProfileServiceClient, ProfileServiceAsyncClient,]
+)
+def test_profile_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.ProfileServiceGrpcTransport, "grpc"),
+ (transports.ProfileServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_profile_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize(
+ "client_class", [ProfileServiceClient, ProfileServiceAsyncClient,]
)
def test_profile_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_profile_service_client_get_transport_class():
transport = ProfileServiceClient.get_transport_class()
- assert transport == transports.ProfileServiceGrpcTransport
+ available_transports = [
+ transports.ProfileServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = ProfileServiceClient.get_transport_class("grpc")
assert transport == transports.ProfileServiceGrpcTransport
@@ -150,7 +219,7 @@ def test_profile_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(ProfileServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -169,7 +238,7 @@ def test_profile_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -185,7 +254,7 @@ def test_profile_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -201,7 +270,7 @@ def test_profile_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -229,7 +298,7 @@ def test_profile_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -280,29 +349,25 @@ def test_profile_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -311,66 +376,53 @@ def test_profile_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -396,7 +448,7 @@ def test_profile_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -426,7 +478,7 @@ def test_profile_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -445,7 +497,7 @@ def test_profile_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -455,7 +507,7 @@ def test_list_profiles(
transport: str = "grpc", request_type=profile_service.ListProfilesRequest
):
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -468,19 +520,15 @@ def test_list_profiles(
call.return_value = profile_service.ListProfilesResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_profiles(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.ListProfilesRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListProfilesPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -488,12 +536,27 @@ def test_list_profiles_from_dict():
test_list_profiles(request_type=dict)
+def test_list_profiles_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ProfileServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_profiles), "__call__") as call:
+ client.list_profiles()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == profile_service.ListProfilesRequest()
+
+
@pytest.mark.asyncio
async def test_list_profiles_async(
transport: str = "grpc_asyncio", request_type=profile_service.ListProfilesRequest
):
client = ProfileServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -508,18 +571,15 @@ async def test_list_profiles_async(
next_page_token="next_page_token_value",
)
)
-
response = await client.list_profiles(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.ListProfilesRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListProfilesAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -529,17 +589,17 @@ async def test_list_profiles_async_from_dict():
def test_list_profiles_field_headers():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.ListProfilesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_profiles), "__call__") as call:
call.return_value = profile_service.ListProfilesResponse()
-
client.list_profiles(request)
# Establish that the underlying gRPC stub method was called.
@@ -554,11 +614,14 @@ def test_list_profiles_field_headers():
@pytest.mark.asyncio
async def test_list_profiles_field_headers_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.ListProfilesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -566,7 +629,6 @@ async def test_list_profiles_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
profile_service.ListProfilesResponse()
)
-
await client.list_profiles(request)
# Establish that the underlying gRPC stub method was called.
@@ -580,13 +642,12 @@ async def test_list_profiles_field_headers_async():
def test_list_profiles_flattened():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_profiles), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = profile_service.ListProfilesResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_profiles(parent="parent_value",)
@@ -595,12 +656,11 @@ def test_list_profiles_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
def test_list_profiles_flattened_error():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -612,7 +672,9 @@ def test_list_profiles_flattened_error():
@pytest.mark.asyncio
async def test_list_profiles_flattened_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_profiles), "__call__") as call:
@@ -630,13 +692,14 @@ async def test_list_profiles_flattened_async():
# 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_profiles_flattened_error_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -647,7 +710,7 @@ async def test_list_profiles_flattened_error_async():
def test_list_profiles_pager():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_profiles), "__call__") as call:
@@ -681,7 +744,7 @@ def test_list_profiles_pager():
def test_list_profiles_pages():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_profiles), "__call__") as call:
@@ -707,7 +770,7 @@ def test_list_profiles_pages():
@pytest.mark.asyncio
async def test_list_profiles_async_pager():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -740,7 +803,7 @@ async def test_list_profiles_async_pager():
@pytest.mark.asyncio
async def test_list_profiles_async_pages():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -772,7 +835,7 @@ def test_create_profile(
transport: str = "grpc", request_type=profile_service.CreateProfileRequest
):
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -793,35 +856,23 @@ def test_create_profile(
processed=True,
keyword_snippet="keyword_snippet_value",
)
-
response = client.create_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.CreateProfileRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_profile.Profile)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.source == "source_value"
-
assert response.uri == "uri_value"
-
assert response.group_id == "group_id_value"
-
assert response.applications == ["applications_value"]
-
assert response.assignments == ["assignments_value"]
-
assert response.processed is True
-
assert response.keyword_snippet == "keyword_snippet_value"
@@ -829,12 +880,27 @@ def test_create_profile_from_dict():
test_create_profile(request_type=dict)
+def test_create_profile_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ProfileServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_profile), "__call__") as call:
+ client.create_profile()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == profile_service.CreateProfileRequest()
+
+
@pytest.mark.asyncio
async def test_create_profile_async(
transport: str = "grpc_asyncio", request_type=profile_service.CreateProfileRequest
):
client = ProfileServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -857,34 +923,23 @@ async def test_create_profile_async(
keyword_snippet="keyword_snippet_value",
)
)
-
response = await client.create_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.CreateProfileRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_profile.Profile)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.source == "source_value"
-
assert response.uri == "uri_value"
-
assert response.group_id == "group_id_value"
-
assert response.applications == ["applications_value"]
-
assert response.assignments == ["assignments_value"]
-
assert response.processed is True
-
assert response.keyword_snippet == "keyword_snippet_value"
@@ -894,17 +949,17 @@ async def test_create_profile_async_from_dict():
def test_create_profile_field_headers():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.CreateProfileRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_profile), "__call__") as call:
call.return_value = gct_profile.Profile()
-
client.create_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -919,17 +974,19 @@ def test_create_profile_field_headers():
@pytest.mark.asyncio
async def test_create_profile_field_headers_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.CreateProfileRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_profile), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_profile.Profile())
-
await client.create_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -943,13 +1000,12 @@ async def test_create_profile_field_headers_async():
def test_create_profile_flattened():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_profile), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_profile.Profile()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_profile(
@@ -960,14 +1016,12 @@ def test_create_profile_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].profile == gct_profile.Profile(name="name_value")
def test_create_profile_flattened_error():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -981,7 +1035,9 @@ def test_create_profile_flattened_error():
@pytest.mark.asyncio
async def test_create_profile_flattened_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_profile), "__call__") as call:
@@ -999,15 +1055,15 @@ async def test_create_profile_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].profile == gct_profile.Profile(name="name_value")
@pytest.mark.asyncio
async def test_create_profile_flattened_error_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1023,7 +1079,7 @@ def test_get_profile(
transport: str = "grpc", request_type=profile_service.GetProfileRequest
):
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1044,35 +1100,23 @@ def test_get_profile(
processed=True,
keyword_snippet="keyword_snippet_value",
)
-
response = client.get_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.GetProfileRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, profile.Profile)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.source == "source_value"
-
assert response.uri == "uri_value"
-
assert response.group_id == "group_id_value"
-
assert response.applications == ["applications_value"]
-
assert response.assignments == ["assignments_value"]
-
assert response.processed is True
-
assert response.keyword_snippet == "keyword_snippet_value"
@@ -1080,12 +1124,27 @@ def test_get_profile_from_dict():
test_get_profile(request_type=dict)
+def test_get_profile_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ProfileServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_profile), "__call__") as call:
+ client.get_profile()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == profile_service.GetProfileRequest()
+
+
@pytest.mark.asyncio
async def test_get_profile_async(
transport: str = "grpc_asyncio", request_type=profile_service.GetProfileRequest
):
client = ProfileServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1108,34 +1167,23 @@ async def test_get_profile_async(
keyword_snippet="keyword_snippet_value",
)
)
-
response = await client.get_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.GetProfileRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, profile.Profile)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.source == "source_value"
-
assert response.uri == "uri_value"
-
assert response.group_id == "group_id_value"
-
assert response.applications == ["applications_value"]
-
assert response.assignments == ["assignments_value"]
-
assert response.processed is True
-
assert response.keyword_snippet == "keyword_snippet_value"
@@ -1145,17 +1193,17 @@ async def test_get_profile_async_from_dict():
def test_get_profile_field_headers():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.GetProfileRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_profile), "__call__") as call:
call.return_value = profile.Profile()
-
client.get_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -1170,17 +1218,19 @@ def test_get_profile_field_headers():
@pytest.mark.asyncio
async def test_get_profile_field_headers_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.GetProfileRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_profile), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(profile.Profile())
-
await client.get_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -1194,13 +1244,12 @@ async def test_get_profile_field_headers_async():
def test_get_profile_flattened():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_profile), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = profile.Profile()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_profile(name="name_value",)
@@ -1209,12 +1258,11 @@ def test_get_profile_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_profile_flattened_error():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1226,7 +1274,9 @@ def test_get_profile_flattened_error():
@pytest.mark.asyncio
async def test_get_profile_flattened_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_profile), "__call__") as call:
@@ -1242,13 +1292,14 @@ async def test_get_profile_flattened_async():
# 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_profile_flattened_error_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1262,7 +1313,7 @@ def test_update_profile(
transport: str = "grpc", request_type=profile_service.UpdateProfileRequest
):
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1283,35 +1334,23 @@ def test_update_profile(
processed=True,
keyword_snippet="keyword_snippet_value",
)
-
response = client.update_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.UpdateProfileRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_profile.Profile)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.source == "source_value"
-
assert response.uri == "uri_value"
-
assert response.group_id == "group_id_value"
-
assert response.applications == ["applications_value"]
-
assert response.assignments == ["assignments_value"]
-
assert response.processed is True
-
assert response.keyword_snippet == "keyword_snippet_value"
@@ -1319,12 +1358,27 @@ def test_update_profile_from_dict():
test_update_profile(request_type=dict)
+def test_update_profile_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ProfileServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_profile), "__call__") as call:
+ client.update_profile()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == profile_service.UpdateProfileRequest()
+
+
@pytest.mark.asyncio
async def test_update_profile_async(
transport: str = "grpc_asyncio", request_type=profile_service.UpdateProfileRequest
):
client = ProfileServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1347,34 +1401,23 @@ async def test_update_profile_async(
keyword_snippet="keyword_snippet_value",
)
)
-
response = await client.update_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.UpdateProfileRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_profile.Profile)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.source == "source_value"
-
assert response.uri == "uri_value"
-
assert response.group_id == "group_id_value"
-
assert response.applications == ["applications_value"]
-
assert response.assignments == ["assignments_value"]
-
assert response.processed is True
-
assert response.keyword_snippet == "keyword_snippet_value"
@@ -1384,17 +1427,17 @@ async def test_update_profile_async_from_dict():
def test_update_profile_field_headers():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.UpdateProfileRequest()
+
request.profile.name = "profile.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_profile), "__call__") as call:
call.return_value = gct_profile.Profile()
-
client.update_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -1411,17 +1454,19 @@ def test_update_profile_field_headers():
@pytest.mark.asyncio
async def test_update_profile_field_headers_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.UpdateProfileRequest()
+
request.profile.name = "profile.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_profile), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_profile.Profile())
-
await client.update_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -1437,13 +1482,12 @@ async def test_update_profile_field_headers_async():
def test_update_profile_flattened():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_profile), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_profile.Profile()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_profile(profile=gct_profile.Profile(name="name_value"),)
@@ -1452,12 +1496,11 @@ def test_update_profile_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].profile == gct_profile.Profile(name="name_value")
def test_update_profile_flattened_error():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1470,7 +1513,9 @@ def test_update_profile_flattened_error():
@pytest.mark.asyncio
async def test_update_profile_flattened_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_profile), "__call__") as call:
@@ -1488,13 +1533,14 @@ async def test_update_profile_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].profile == gct_profile.Profile(name="name_value")
@pytest.mark.asyncio
async def test_update_profile_flattened_error_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1509,7 +1555,7 @@ def test_delete_profile(
transport: str = "grpc", request_type=profile_service.DeleteProfileRequest
):
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1520,13 +1566,11 @@ def test_delete_profile(
with mock.patch.object(type(client.transport.delete_profile), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.DeleteProfileRequest()
# Establish that the response is the type that we expect.
@@ -1537,12 +1581,27 @@ def test_delete_profile_from_dict():
test_delete_profile(request_type=dict)
+def test_delete_profile_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ProfileServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_profile), "__call__") as call:
+ client.delete_profile()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == profile_service.DeleteProfileRequest()
+
+
@pytest.mark.asyncio
async def test_delete_profile_async(
transport: str = "grpc_asyncio", request_type=profile_service.DeleteProfileRequest
):
client = ProfileServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1553,13 +1612,11 @@ async def test_delete_profile_async(
with mock.patch.object(type(client.transport.delete_profile), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_profile(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.DeleteProfileRequest()
# Establish that the response is the type that we expect.
@@ -1572,17 +1629,17 @@ async def test_delete_profile_async_from_dict():
def test_delete_profile_field_headers():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.DeleteProfileRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_profile), "__call__") as call:
call.return_value = None
-
client.delete_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -1597,17 +1654,19 @@ def test_delete_profile_field_headers():
@pytest.mark.asyncio
async def test_delete_profile_field_headers_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.DeleteProfileRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_profile), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_profile(request)
# Establish that the underlying gRPC stub method was called.
@@ -1621,13 +1680,12 @@ async def test_delete_profile_field_headers_async():
def test_delete_profile_flattened():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_profile), "__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_profile(name="name_value",)
@@ -1636,12 +1694,11 @@ def test_delete_profile_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_profile_flattened_error():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1653,7 +1710,9 @@ def test_delete_profile_flattened_error():
@pytest.mark.asyncio
async def test_delete_profile_flattened_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_profile), "__call__") as call:
@@ -1669,13 +1728,14 @@ async def test_delete_profile_flattened_async():
# 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_profile_flattened_error_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1689,7 +1749,7 @@ def test_search_profiles(
transport: str = "grpc", request_type=profile_service.SearchProfilesRequest
):
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1704,23 +1764,17 @@ def test_search_profiles(
next_page_token="next_page_token_value",
result_set_id="result_set_id_value",
)
-
response = client.search_profiles(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.SearchProfilesRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.SearchProfilesPager)
-
assert response.estimated_total_size == 2141
-
assert response.next_page_token == "next_page_token_value"
-
assert response.result_set_id == "result_set_id_value"
@@ -1728,12 +1782,27 @@ def test_search_profiles_from_dict():
test_search_profiles(request_type=dict)
+def test_search_profiles_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = ProfileServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.search_profiles), "__call__") as call:
+ client.search_profiles()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == profile_service.SearchProfilesRequest()
+
+
@pytest.mark.asyncio
async def test_search_profiles_async(
transport: str = "grpc_asyncio", request_type=profile_service.SearchProfilesRequest
):
client = ProfileServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1750,22 +1819,17 @@ async def test_search_profiles_async(
result_set_id="result_set_id_value",
)
)
-
response = await client.search_profiles(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == profile_service.SearchProfilesRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.SearchProfilesAsyncPager)
-
assert response.estimated_total_size == 2141
-
assert response.next_page_token == "next_page_token_value"
-
assert response.result_set_id == "result_set_id_value"
@@ -1775,17 +1839,17 @@ async def test_search_profiles_async_from_dict():
def test_search_profiles_field_headers():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.SearchProfilesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.search_profiles), "__call__") as call:
call.return_value = profile_service.SearchProfilesResponse()
-
client.search_profiles(request)
# Establish that the underlying gRPC stub method was called.
@@ -1800,11 +1864,14 @@ def test_search_profiles_field_headers():
@pytest.mark.asyncio
async def test_search_profiles_field_headers_async():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = profile_service.SearchProfilesRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1812,7 +1879,6 @@ async def test_search_profiles_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
profile_service.SearchProfilesResponse()
)
-
await client.search_profiles(request)
# Establish that the underlying gRPC stub method was called.
@@ -1826,7 +1892,7 @@ async def test_search_profiles_field_headers_async():
def test_search_profiles_pager():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.search_profiles), "__call__") as call:
@@ -1870,7 +1936,7 @@ def test_search_profiles_pager():
def test_search_profiles_pages():
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.search_profiles), "__call__") as call:
@@ -1906,7 +1972,7 @@ def test_search_profiles_pages():
@pytest.mark.asyncio
async def test_search_profiles_async_pager():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1949,7 +2015,7 @@ async def test_search_profiles_async_pager():
@pytest.mark.asyncio
async def test_search_profiles_async_pages():
- client = ProfileServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = ProfileServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1990,16 +2056,16 @@ async def test_search_profiles_async_pages():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.ProfileServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.ProfileServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = ProfileServiceClient(
@@ -2009,7 +2075,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.ProfileServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = ProfileServiceClient(
@@ -2020,7 +2086,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.ProfileServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = ProfileServiceClient(transport=transport)
assert client.transport is transport
@@ -2029,13 +2095,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.ProfileServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.ProfileServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -2050,23 +2116,23 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = ProfileServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = ProfileServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.ProfileServiceGrpcTransport,)
def test_profile_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.ProfileServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -2078,7 +2144,7 @@ def test_profile_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.ProfileServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -2096,15 +2162,40 @@ def test_profile_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_profile_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4beta1.services.profile_service.transports.ProfileServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.ProfileServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_profile_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4beta1.services.profile_service.transports.ProfileServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.ProfileServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -2120,19 +2211,36 @@ def test_profile_service_base_transport_with_credentials_file():
def test_profile_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4beta1.services.profile_service.transports.ProfileServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.ProfileServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_profile_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ ProfileServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_profile_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
ProfileServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -2143,14 +2251,44 @@ def test_profile_service_auth_adc():
)
-def test_profile_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ProfileServiceGrpcTransport,
+ transports.ProfileServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_profile_service_transport_auth_adc(transport_class):
# 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.ProfileServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ProfileServiceGrpcTransport,
+ transports.ProfileServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_profile_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -2160,9 +2298,92 @@ def test_profile_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.ProfileServiceGrpcTransport, grpc_helpers),
+ (transports.ProfileServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_profile_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ProfileServiceGrpcTransport,
+ transports.ProfileServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_profile_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_profile_service_host_no_port():
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -2170,7 +2391,7 @@ def test_profile_service_host_no_port():
def test_profile_service_host_with_port():
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -2179,7 +2400,7 @@ def test_profile_service_host_with_port():
def test_profile_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.ProfileServiceGrpcTransport(
@@ -2191,7 +2412,7 @@ def test_profile_service_grpc_transport_channel():
def test_profile_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.ProfileServiceGrpcAsyncIOTransport(
@@ -2202,6 +2423,8 @@ def test_profile_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -2216,7 +2439,7 @@ def test_profile_service_transport_channel_mtls_with_client_cert_source(
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -2224,9 +2447,9 @@ def test_profile_service_transport_channel_mtls_with_client_cert_source(
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -2242,10 +2465,7 @@ def test_profile_service_transport_channel_mtls_with_client_cert_source(
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2257,6 +2477,8 @@ def test_profile_service_transport_channel_mtls_with_client_cert_source(
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -2272,7 +2494,7 @@ def test_profile_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -2290,10 +2512,7 @@ def test_profile_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -2308,7 +2527,6 @@ def test_profile_path():
project = "squid"
tenant = "clam"
profile = "whelk"
-
expected = "projects/{project}/tenants/{tenant}/profiles/{profile}".format(
project=project, tenant=tenant, profile=profile,
)
@@ -2332,7 +2550,6 @@ def test_parse_profile_path():
def test_tenant_path():
project = "cuttlefish"
tenant = "mussel"
-
expected = "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@@ -2354,7 +2571,6 @@ def test_parse_tenant_path():
def test_common_billing_account_path():
billing_account = "scallop"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -2375,7 +2591,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "squid"
-
expected = "folders/{folder}".format(folder=folder,)
actual = ProfileServiceClient.common_folder_path(folder)
assert expected == actual
@@ -2394,7 +2609,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "whelk"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = ProfileServiceClient.common_organization_path(organization)
assert expected == actual
@@ -2413,7 +2627,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "oyster"
-
expected = "projects/{project}".format(project=project,)
actual = ProfileServiceClient.common_project_path(project)
assert expected == actual
@@ -2433,7 +2646,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "cuttlefish"
location = "mussel"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -2460,7 +2672,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.ProfileServiceTransport, "_prep_wrapped_messages"
) as prep:
client = ProfileServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -2469,6 +2681,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = ProfileServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
diff --git a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py
index 62a13dd4..b09d185d 100644
--- a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py
+++ b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
import os
import mock
+import packaging.version
import grpc
from grpc.experimental import aio
@@ -24,23 +23,41 @@
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 exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
-from google.auth import credentials
+from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.talent_v4beta1.services.tenant_service import TenantServiceAsyncClient
from google.cloud.talent_v4beta1.services.tenant_service import TenantServiceClient
from google.cloud.talent_v4beta1.services.tenant_service import pagers
from google.cloud.talent_v4beta1.services.tenant_service import transports
+from google.cloud.talent_v4beta1.services.tenant_service.transports.base import (
+ _GOOGLE_AUTH_VERSION,
+)
from google.cloud.talent_v4beta1.types import tenant
from google.cloud.talent_v4beta1.types import tenant as gct_tenant
from google.cloud.talent_v4beta1.types import tenant_service
from google.oauth2 import service_account
-from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+from google.protobuf import field_mask_pb2 # type: ignore
+import google.auth
+
+
+# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
+# through google-api-core:
+# - Delete the auth "less than" test cases
+# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
+requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth < 1.25.0",
+)
+requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
+ packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
+ reason="This test requires google-auth >= 1.25.0",
+)
def client_cert_source_callback():
@@ -88,26 +105,78 @@ def test__get_default_mtls_endpoint():
@pytest.mark.parametrize(
- "client_class", [TenantServiceClient, TenantServiceAsyncClient]
+ "client_class", [TenantServiceClient, TenantServiceAsyncClient,]
+)
+def test_tenant_service_client_from_service_account_info(client_class):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == "jobs.googleapis.com:443"
+
+
+@pytest.mark.parametrize(
+ "client_class", [TenantServiceClient, TenantServiceAsyncClient,]
+)
+def test_tenant_service_client_service_account_always_use_jwt(client_class):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ client = client_class(credentials=creds)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.TenantServiceGrpcTransport, "grpc"),
+ (transports.TenantServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ ],
+)
+def test_tenant_service_client_service_account_always_use_jwt_true(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+
+@pytest.mark.parametrize(
+ "client_class", [TenantServiceClient, TenantServiceAsyncClient,]
)
def test_tenant_service_client_from_service_account_file(client_class):
- creds = credentials.AnonymousCredentials()
+ creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
assert client.transport._host == "jobs.googleapis.com:443"
def test_tenant_service_client_get_transport_class():
transport = TenantServiceClient.get_transport_class()
- assert transport == transports.TenantServiceGrpcTransport
+ available_transports = [
+ transports.TenantServiceGrpcTransport,
+ ]
+ assert transport in available_transports
transport = TenantServiceClient.get_transport_class("grpc")
assert transport == transports.TenantServiceGrpcTransport
@@ -139,7 +208,7 @@ def test_tenant_service_client_client_options(
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(TenantServiceClient, "get_transport_class") as gtc:
- transport = transport_class(credentials=credentials.AnonymousCredentials())
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
@@ -158,7 +227,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -174,7 +243,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -190,7 +259,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -218,7 +287,7 @@ def test_tenant_service_client_client_options(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -269,29 +338,25 @@ def test_tenant_service_client_mtls_env_auto(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
- ssl_channel_creds = mock.Mock()
- with mock.patch(
- "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
- ):
- patched.return_value = None
- client = client_class(client_options=options)
+ patched.return_value = None
+ client = client_class(client_options=options)
- if use_client_cert_env == "false":
- expected_ssl_channel_creds = None
- expected_host = client.DEFAULT_ENDPOINT
- else:
- expected_ssl_channel_creds = ssl_channel_creds
- expected_host = client.DEFAULT_MTLS_ENDPOINT
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
@@ -300,66 +365,53 @@ def test_tenant_service_client_mtls_env_auto(
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
):
with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.ssl_credentials",
- new_callable=mock.PropertyMock,
- ) as ssl_credentials_mock:
- if use_client_cert_env == "false":
- is_mtls_mock.return_value = False
- ssl_credentials_mock.return_value = None
- expected_host = client.DEFAULT_ENDPOINT
- expected_ssl_channel_creds = None
- else:
- is_mtls_mock.return_value = True
- ssl_credentials_mock.return_value = mock.Mock()
- expected_host = client.DEFAULT_MTLS_ENDPOINT
- expected_ssl_channel_creds = (
- ssl_credentials_mock.return_value
- )
-
- patched.return_value = None
- client = client_class()
- patched.assert_called_once_with(
- credentials=None,
- credentials_file=None,
- host=expected_host,
- scopes=None,
- ssl_channel_credentials=expected_ssl_channel_creds,
- quota_project_id=None,
- client_info=transports.base.DEFAULT_CLIENT_INFO,
- )
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
- # Check the case client_cert_source and ADC client cert are not provided.
- with mock.patch.dict(
- os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
- ):
- with mock.patch.object(transport_class, "__init__") as patched:
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
- ):
- with mock.patch(
- "google.auth.transport.grpc.SslCredentials.is_mtls",
- new_callable=mock.PropertyMock,
- ) as is_mtls_mock:
- is_mtls_mock.return_value = False
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
- host=client.DEFAULT_ENDPOINT,
+ host=expected_host,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
@@ -385,7 +437,7 @@ def test_tenant_service_client_client_options_scopes(
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -415,7 +467,7 @@ def test_tenant_service_client_client_options_credentials_file(
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -434,7 +486,7 @@ def test_tenant_service_client_client_options_from_dict():
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
- ssl_channel_credentials=None,
+ client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@@ -444,7 +496,7 @@ def test_create_tenant(
transport: str = "grpc", request_type=tenant_service.CreateTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -462,25 +514,18 @@ def test_create_tenant(
"keyword_searchable_profile_custom_attributes_value"
],
)
-
response = client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.CreateTenantRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.usage_type == gct_tenant.Tenant.DataUsageType.AGGREGATED
-
assert response.keyword_searchable_profile_custom_attributes == [
"keyword_searchable_profile_custom_attributes_value"
]
@@ -490,12 +535,27 @@ def test_create_tenant_from_dict():
test_create_tenant(request_type=dict)
+def test_create_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
+ client.create_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.CreateTenantRequest()
+
+
@pytest.mark.asyncio
async def test_create_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.CreateTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -515,24 +575,18 @@ async def test_create_tenant_async(
],
)
)
-
response = await client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.CreateTenantRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.usage_type == gct_tenant.Tenant.DataUsageType.AGGREGATED
-
assert response.keyword_searchable_profile_custom_attributes == [
"keyword_searchable_profile_custom_attributes_value"
]
@@ -544,17 +598,17 @@ async def test_create_tenant_async_from_dict():
def test_create_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.CreateTenantRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
call.return_value = gct_tenant.Tenant()
-
client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -569,17 +623,19 @@ def test_create_tenant_field_headers():
@pytest.mark.asyncio
async def test_create_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.CreateTenantRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_tenant.Tenant())
-
await client.create_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -593,13 +649,12 @@ async def test_create_tenant_field_headers_async():
def test_create_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_tenant.Tenant()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.create_tenant(
@@ -610,14 +665,12 @@ def test_create_tenant_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
def test_create_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -631,7 +684,9 @@ def test_create_tenant_flattened_error():
@pytest.mark.asyncio
async def test_create_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.create_tenant), "__call__") as call:
@@ -649,15 +704,15 @@ async def test_create_tenant_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
@pytest.mark.asyncio
async def test_create_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -673,7 +728,7 @@ def test_get_tenant(
transport: str = "grpc", request_type=tenant_service.GetTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -691,25 +746,18 @@ def test_get_tenant(
"keyword_searchable_profile_custom_attributes_value"
],
)
-
response = client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.GetTenantRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.usage_type == tenant.Tenant.DataUsageType.AGGREGATED
-
assert response.keyword_searchable_profile_custom_attributes == [
"keyword_searchable_profile_custom_attributes_value"
]
@@ -719,12 +767,27 @@ def test_get_tenant_from_dict():
test_get_tenant(request_type=dict)
+def test_get_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
+ client.get_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.GetTenantRequest()
+
+
@pytest.mark.asyncio
async def test_get_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.GetTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -744,24 +807,18 @@ async def test_get_tenant_async(
],
)
)
-
response = await client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.GetTenantRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.usage_type == tenant.Tenant.DataUsageType.AGGREGATED
-
assert response.keyword_searchable_profile_custom_attributes == [
"keyword_searchable_profile_custom_attributes_value"
]
@@ -773,17 +830,17 @@ async def test_get_tenant_async_from_dict():
def test_get_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.GetTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
call.return_value = tenant.Tenant()
-
client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -798,17 +855,19 @@ def test_get_tenant_field_headers():
@pytest.mark.asyncio
async def test_get_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.GetTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tenant.Tenant())
-
await client.get_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -822,13 +881,12 @@ async def test_get_tenant_field_headers_async():
def test_get_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = tenant.Tenant()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_tenant(name="name_value",)
@@ -837,12 +895,11 @@ def test_get_tenant_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_get_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -854,7 +911,9 @@ def test_get_tenant_flattened_error():
@pytest.mark.asyncio
async def test_get_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.get_tenant), "__call__") as call:
@@ -870,13 +929,14 @@ async def test_get_tenant_flattened_async():
# 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_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -890,7 +950,7 @@ def test_update_tenant(
transport: str = "grpc", request_type=tenant_service.UpdateTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -908,25 +968,18 @@ def test_update_tenant(
"keyword_searchable_profile_custom_attributes_value"
],
)
-
response = client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.UpdateTenantRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.usage_type == gct_tenant.Tenant.DataUsageType.AGGREGATED
-
assert response.keyword_searchable_profile_custom_attributes == [
"keyword_searchable_profile_custom_attributes_value"
]
@@ -936,12 +989,27 @@ def test_update_tenant_from_dict():
test_update_tenant(request_type=dict)
+def test_update_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
+ client.update_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.UpdateTenantRequest()
+
+
@pytest.mark.asyncio
async def test_update_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.UpdateTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -961,24 +1029,18 @@ async def test_update_tenant_async(
],
)
)
-
response = await client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.UpdateTenantRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, gct_tenant.Tenant)
-
assert response.name == "name_value"
-
assert response.external_id == "external_id_value"
-
assert response.usage_type == gct_tenant.Tenant.DataUsageType.AGGREGATED
-
assert response.keyword_searchable_profile_custom_attributes == [
"keyword_searchable_profile_custom_attributes_value"
]
@@ -990,17 +1052,17 @@ async def test_update_tenant_async_from_dict():
def test_update_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.UpdateTenantRequest()
+
request.tenant.name = "tenant.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
call.return_value = gct_tenant.Tenant()
-
client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -1015,17 +1077,19 @@ def test_update_tenant_field_headers():
@pytest.mark.asyncio
async def test_update_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.UpdateTenantRequest()
+
request.tenant.name = "tenant.name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gct_tenant.Tenant())
-
await client.update_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -1039,13 +1103,12 @@ async def test_update_tenant_field_headers_async():
def test_update_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = gct_tenant.Tenant()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.update_tenant(tenant=gct_tenant.Tenant(name="name_value"),)
@@ -1054,12 +1117,11 @@ def test_update_tenant_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
def test_update_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1072,7 +1134,9 @@ def test_update_tenant_flattened_error():
@pytest.mark.asyncio
async def test_update_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.update_tenant), "__call__") as call:
@@ -1090,13 +1154,14 @@ async def test_update_tenant_flattened_async():
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0].tenant == gct_tenant.Tenant(name="name_value")
@pytest.mark.asyncio
async def test_update_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1111,7 +1176,7 @@ def test_delete_tenant(
transport: str = "grpc", request_type=tenant_service.DeleteTenantRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1122,13 +1187,11 @@ def test_delete_tenant(
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = None
-
response = client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.DeleteTenantRequest()
# Establish that the response is the type that we expect.
@@ -1139,12 +1202,27 @@ def test_delete_tenant_from_dict():
test_delete_tenant(request_type=dict)
+def test_delete_tenant_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
+ client.delete_tenant()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.DeleteTenantRequest()
+
+
@pytest.mark.asyncio
async def test_delete_tenant_async(
transport: str = "grpc_asyncio", request_type=tenant_service.DeleteTenantRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1155,13 +1233,11 @@ async def test_delete_tenant_async(
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
response = await client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.DeleteTenantRequest()
# Establish that the response is the type that we expect.
@@ -1174,17 +1250,17 @@ async def test_delete_tenant_async_from_dict():
def test_delete_tenant_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.DeleteTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
call.return_value = None
-
client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -1199,17 +1275,19 @@ def test_delete_tenant_field_headers():
@pytest.mark.asyncio
async def test_delete_tenant_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.DeleteTenantRequest()
+
request.name = "name/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
-
await client.delete_tenant(request)
# Establish that the underlying gRPC stub method was called.
@@ -1223,13 +1301,12 @@ async def test_delete_tenant_field_headers_async():
def test_delete_tenant_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__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_tenant(name="name_value",)
@@ -1238,12 +1315,11 @@ def test_delete_tenant_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].name == "name_value"
def test_delete_tenant_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1255,7 +1331,9 @@ def test_delete_tenant_flattened_error():
@pytest.mark.asyncio
async def test_delete_tenant_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.delete_tenant), "__call__") as call:
@@ -1271,13 +1349,14 @@ async def test_delete_tenant_flattened_async():
# 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_tenant_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1291,7 +1370,7 @@ def test_list_tenants(
transport: str = "grpc", request_type=tenant_service.ListTenantsRequest
):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1304,19 +1383,15 @@ def test_list_tenants(
call.return_value = tenant_service.ListTenantsResponse(
next_page_token="next_page_token_value",
)
-
response = client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.ListTenantsRequest()
# Establish that the response is the type that we expect.
-
assert isinstance(response, pagers.ListTenantsPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1324,12 +1399,27 @@ def test_list_tenants_from_dict():
test_list_tenants(request_type=dict)
+def test_list_tenants_empty_call():
+ # This test is a coverage failsafe to make sure that totally empty calls,
+ # i.e. request == None and no flattened fields passed, work.
+ client = TenantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
+ client.list_tenants()
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == tenant_service.ListTenantsRequest()
+
+
@pytest.mark.asyncio
async def test_list_tenants_async(
transport: str = "grpc_asyncio", request_type=tenant_service.ListTenantsRequest
):
client = TenantServiceAsyncClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
@@ -1342,18 +1432,15 @@ async def test_list_tenants_async(
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
tenant_service.ListTenantsResponse(next_page_token="next_page_token_value",)
)
-
response = await client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
-
assert args[0] == tenant_service.ListTenantsRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListTenantsAsyncPager)
-
assert response.next_page_token == "next_page_token_value"
@@ -1363,17 +1450,17 @@ async def test_list_tenants_async_from_dict():
def test_list_tenants_field_headers():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.ListTenantsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
call.return_value = tenant_service.ListTenantsResponse()
-
client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
@@ -1388,11 +1475,14 @@ def test_list_tenants_field_headers():
@pytest.mark.asyncio
async def test_list_tenants_field_headers_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = tenant_service.ListTenantsRequest()
+
request.parent = "parent/value"
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1400,7 +1490,6 @@ async def test_list_tenants_field_headers_async():
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
tenant_service.ListTenantsResponse()
)
-
await client.list_tenants(request)
# Establish that the underlying gRPC stub method was called.
@@ -1414,13 +1503,12 @@ async def test_list_tenants_field_headers_async():
def test_list_tenants_flattened():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
# Designate an appropriate return value for the call.
call.return_value = tenant_service.ListTenantsResponse()
-
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_tenants(parent="parent_value",)
@@ -1429,12 +1517,11 @@ def test_list_tenants_flattened():
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
-
assert args[0].parent == "parent_value"
def test_list_tenants_flattened_error():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1446,7 +1533,9 @@ def test_list_tenants_flattened_error():
@pytest.mark.asyncio
async def test_list_tenants_flattened_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
@@ -1464,13 +1553,14 @@ async def test_list_tenants_flattened_async():
# 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_tenants_flattened_error_async():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
# Attempting to call a method with both a request object and flattened
# fields is an error.
@@ -1481,7 +1571,7 @@ async def test_list_tenants_flattened_error_async():
def test_list_tenants_pager():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
@@ -1515,7 +1605,7 @@ def test_list_tenants_pager():
def test_list_tenants_pages():
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(type(client.transport.list_tenants), "__call__") as call:
@@ -1541,7 +1631,7 @@ def test_list_tenants_pages():
@pytest.mark.asyncio
async def test_list_tenants_async_pager():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1574,7 +1664,7 @@ async def test_list_tenants_async_pager():
@pytest.mark.asyncio
async def test_list_tenants_async_pages():
- client = TenantServiceAsyncClient(credentials=credentials.AnonymousCredentials,)
+ client = TenantServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
@@ -1605,16 +1695,16 @@ async def test_list_tenants_async_pages():
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TenantServiceClient(
@@ -1624,7 +1714,7 @@ def test_credentials_transport_error():
# It is an error to provide scopes and a transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = TenantServiceClient(
@@ -1635,7 +1725,7 @@ def test_credentials_transport_error():
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
client = TenantServiceClient(transport=transport)
assert client.transport is transport
@@ -1644,13 +1734,13 @@ def test_transport_instance():
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.TenantServiceGrpcTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
transport = transports.TenantServiceGrpcAsyncIOTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
@@ -1665,23 +1755,23 @@ def test_transport_get_channel():
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
- with mock.patch.object(auth, "default") as adc:
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
- client = TenantServiceClient(credentials=credentials.AnonymousCredentials(),)
+ client = TenantServiceClient(credentials=ga_credentials.AnonymousCredentials(),)
assert isinstance(client.transport, transports.TenantServiceGrpcTransport,)
def test_tenant_service_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
- with pytest.raises(exceptions.DuplicateCredentialArgs):
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.TenantServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
@@ -1693,7 +1783,7 @@ def test_tenant_service_base_transport():
) as Transport:
Transport.return_value = None
transport = transports.TenantServiceTransport(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
@@ -1710,15 +1800,40 @@ def test_tenant_service_base_transport():
getattr(transport, method)(request=object())
+@requires_google_auth_gte_1_25_0
def test_tenant_service_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
- auth, "load_credentials_from_file"
+ google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.talent_v4beta1.services.tenant_service.transports.TenantServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.TenantServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_tenant_service_base_transport_with_credentials_file_old_google_auth():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds, mock.patch(
+ "google.cloud.talent_v4beta1.services.tenant_service.transports.TenantServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.TenantServiceTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
@@ -1734,19 +1849,36 @@ def test_tenant_service_base_transport_with_credentials_file():
def test_tenant_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
- with mock.patch.object(auth, "default") as adc, mock.patch(
+ with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.talent_v4beta1.services.tenant_service.transports.TenantServiceTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
- adc.return_value = (credentials.AnonymousCredentials(), None)
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.TenantServiceTransport()
adc.assert_called_once()
+@requires_google_auth_gte_1_25_0
def test_tenant_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)
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ TenantServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id=None,
+ )
+
+
+@requires_google_auth_lt_1_25_0
+def test_tenant_service_auth_adc_old_google_auth():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
TenantServiceClient()
adc.assert_called_once_with(
scopes=(
@@ -1757,14 +1889,44 @@ def test_tenant_service_auth_adc():
)
-def test_tenant_service_transport_auth_adc():
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TenantServiceGrpcTransport,
+ transports.TenantServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_gte_1_25_0
+def test_tenant_service_transport_auth_adc(transport_class):
# 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.TenantServiceGrpcTransport(
- host="squid.clam.whelk", quota_project_id="octopus"
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ quota_project_id="octopus",
)
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TenantServiceGrpcTransport,
+ transports.TenantServiceGrpcAsyncIOTransport,
+ ],
+)
+@requires_google_auth_lt_1_25_0
+def test_tenant_service_transport_auth_adc_old_google_auth(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus")
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/cloud-platform",
@@ -1774,9 +1936,92 @@ def test_tenant_service_transport_auth_adc():
)
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.TenantServiceGrpcTransport, grpc_helpers),
+ (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_tenant_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(
+ google.auth, "default", autospec=True
+ ) as adc, mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel:
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "jobs.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/jobs",
+ ),
+ scopes=["1", "2"],
+ default_host="jobs.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.TenantServiceGrpcTransport,
+ transports.TenantServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
def test_tenant_service_host_no_port():
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint="jobs.googleapis.com"),
)
assert client.transport._host == "jobs.googleapis.com:443"
@@ -1784,7 +2029,7 @@ def test_tenant_service_host_no_port():
def test_tenant_service_host_with_port():
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(),
+ credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="jobs.googleapis.com:8000"
),
@@ -1793,7 +2038,7 @@ def test_tenant_service_host_with_port():
def test_tenant_service_grpc_transport_channel():
- channel = grpc.insecure_channel("http://localhost/")
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.TenantServiceGrpcTransport(
@@ -1805,7 +2050,7 @@ def test_tenant_service_grpc_transport_channel():
def test_tenant_service_grpc_asyncio_transport_channel():
- channel = aio.insecure_channel("http://localhost/")
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
# Check that channel is used if provided.
transport = transports.TenantServiceGrpcAsyncIOTransport(
@@ -1816,6 +2061,8 @@ def test_tenant_service_grpc_asyncio_transport_channel():
assert transport._ssl_channel_credentials == None
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -1828,7 +2075,7 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
"grpc.ssl_channel_credentials", autospec=True
) as grpc_ssl_channel_cred:
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
@@ -1836,9 +2083,9 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
- cred = credentials.AnonymousCredentials()
+ cred = ga_credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
- with mock.patch.object(auth, "default") as adc:
+ with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
@@ -1854,10 +2101,7 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -1869,6 +2113,8 @@ def test_tenant_service_transport_channel_mtls_with_client_cert_source(transport
assert transport._ssl_channel_credentials == mock_ssl_cred
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
@pytest.mark.parametrize(
"transport_class",
[
@@ -1884,7 +2130,7 @@ def test_tenant_service_transport_channel_mtls_with_adc(transport_class):
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(
- transport_class, "create_channel", autospec=True
+ transport_class, "create_channel"
) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
@@ -1902,10 +2148,7 @@ def test_tenant_service_transport_channel_mtls_with_adc(transport_class):
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
- scopes=(
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/jobs",
- ),
+ scopes=None,
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
@@ -1919,7 +2162,6 @@ def test_tenant_service_transport_channel_mtls_with_adc(transport_class):
def test_tenant_path():
project = "squid"
tenant = "clam"
-
expected = "projects/{project}/tenants/{tenant}".format(
project=project, tenant=tenant,
)
@@ -1941,7 +2183,6 @@ def test_parse_tenant_path():
def test_common_billing_account_path():
billing_account = "oyster"
-
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -1962,7 +2203,6 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
folder = "cuttlefish"
-
expected = "folders/{folder}".format(folder=folder,)
actual = TenantServiceClient.common_folder_path(folder)
assert expected == actual
@@ -1981,7 +2221,6 @@ def test_parse_common_folder_path():
def test_common_organization_path():
organization = "winkle"
-
expected = "organizations/{organization}".format(organization=organization,)
actual = TenantServiceClient.common_organization_path(organization)
assert expected == actual
@@ -2000,7 +2239,6 @@ def test_parse_common_organization_path():
def test_common_project_path():
project = "scallop"
-
expected = "projects/{project}".format(project=project,)
actual = TenantServiceClient.common_project_path(project)
assert expected == actual
@@ -2020,7 +2258,6 @@ def test_parse_common_project_path():
def test_common_location_path():
project = "squid"
location = "clam"
-
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@@ -2047,7 +2284,7 @@ def test_client_withDEFAULT_CLIENT_INFO():
transports.TenantServiceTransport, "_prep_wrapped_messages"
) as prep:
client = TenantServiceClient(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
@@ -2056,6 +2293,6 @@ def test_client_withDEFAULT_CLIENT_INFO():
) as prep:
transport_class = TenantServiceClient.get_transport_class()
transport = transport_class(
- credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)