From c2c2afdd05f317798a13f43c843071e12a003a68 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 5 Mar 2021 03:42:16 +0100 Subject: [PATCH 01/26] chore(deps): update dependency google.cloud.talent to v2.1.0 (#69) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From bb632f21c24cdca6094f989657ec6e72d4ffb371 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Tue, 23 Mar 2021 10:02:07 -0700 Subject: [PATCH 02/26] chore: update templates (#64) * changes without context autosynth cannot find the source of changes triggered by earlier changes in this repository, or by version upgrades to tools such as linters. * chore(python): fix column sizing issue in docs Source-Author: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Source-Date: Thu Jan 7 11:58:32 2021 -0700 Source-Repo: googleapis/synthtool Source-Sha: f15b57ccfd71106c2299e9b89835fe6e55015662 Source-Link: https://github.com/googleapis/synthtool/commit/f15b57ccfd71106c2299e9b89835fe6e55015662 * chore(python): use 'http' in LICENSE Co-authored-by: Tim Swast Source-Author: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Source-Date: Thu Jan 7 13:05:12 2021 -0700 Source-Repo: googleapis/synthtool Source-Sha: 41a4e56982620d3edcf110d76f4fcdfdec471ac8 Source-Link: https://github.com/googleapis/synthtool/commit/41a4e56982620d3edcf110d76f4fcdfdec471ac8 --- LICENSE | 7 ++++--- docs/_static/custom.css | 7 ++++++- google/cloud/talent_v4/__init__.py | 4 ++-- google/cloud/talent_v4beta1/__init__.py | 4 ++-- synth.metadata | 6 +++--- 5 files changed, 17 insertions(+), 11 deletions(-) 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/docs/_static/custom.css b/docs/_static/custom.css index 0abaf229..bcd37bbd 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,4 +1,9 @@ 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 +} diff --git a/google/cloud/talent_v4/__init__.py b/google/cloud/talent_v4/__init__.py index 5d959d15..1d4b845e 100644 --- a/google/cloud/talent_v4/__init__.py +++ b/google/cloud/talent_v4/__init__.py @@ -101,6 +101,7 @@ "CompensationInfo", "CompleteQueryRequest", "CompleteQueryResponse", + "CompletionClient", "CreateClientEventRequest", "CreateCompanyRequest", "CreateJobRequest", @@ -126,7 +127,6 @@ "JobLevel", "JobQuery", "JobResult", - "JobServiceClient", "JobView", "ListCompaniesRequest", "ListCompaniesResponse", @@ -149,5 +149,5 @@ "UpdateJobRequest", "UpdateTenantRequest", "Visibility", - "CompletionClient", + "JobServiceClient", ) diff --git a/google/cloud/talent_v4beta1/__init__.py b/google/cloud/talent_v4beta1/__init__.py index e486a156..4743ac58 100644 --- a/google/cloud/talent_v4beta1/__init__.py +++ b/google/cloud/talent_v4beta1/__init__.py @@ -186,6 +186,7 @@ "EmployerFilter", "EmploymentRecord", "EmploymentType", + "EventServiceClient", "GetApplicationRequest", "GetCompanyRequest", "GetJobRequest", @@ -243,7 +244,6 @@ "SpellingCorrection", "SummarizedProfile", "Tenant", - "TenantServiceClient", "TimeFilter", "TimestampRange", "UpdateApplicationRequest", @@ -253,5 +253,5 @@ "UpdateTenantRequest", "Visibility", "WorkExperienceFilter", - "EventServiceClient", + "TenantServiceClient", ) diff --git a/synth.metadata b/synth.metadata index c2c125ec..83804676 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-talent.git", - "sha": "d95d9bccf6fca2ee08181d3b63572ca1a4b97eb2" + "sha": "8a53830a77532e25ff0794e9fb5400e4ec01d4f5" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4" + "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "373861061648b5fe5e0ac4f8a38b32d639ee93e4" + "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" } } ], From 095747e8b517769a9caa2df6babf96fd526d0a22 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Tue, 30 Mar 2021 12:33:23 -0700 Subject: [PATCH 03/26] fix: fix retry deadlines (#73) feat: add `from_service_account_info` --- .coveragerc | 31 +- .github/header-checker-lint.yml | 15 + .gitignore | 4 +- .kokoro/build.sh | 26 +- .kokoro/docs/docs-presubmit.cfg | 11 + .kokoro/samples/python3.6/periodic-head.cfg | 11 + .kokoro/samples/python3.7/periodic-head.cfg | 11 + .kokoro/samples/python3.8/periodic-head.cfg | 11 + .kokoro/test-samples-against-head.sh | 28 ++ .kokoro/test-samples-impl.sh | 102 +++++ .kokoro/test-samples.sh | 96 +---- .pre-commit-config.yaml | 2 +- .trampolinerc | 1 + CONTRIBUTING.rst | 22 +- MANIFEST.in | 4 +- UPGRADING.md | 6 +- docs/talent_v4/company_service.rst | 11 + docs/talent_v4/completion.rst | 6 + docs/talent_v4/event_service.rst | 6 + docs/talent_v4/job_service.rst | 11 + docs/talent_v4/services.rst | 22 +- docs/talent_v4/tenant_service.rst | 11 + docs/talent_v4/types.rst | 1 + docs/talent_v4beta1/application_service.rst | 11 + docs/talent_v4beta1/company_service.rst | 11 + docs/talent_v4beta1/completion.rst | 6 + docs/talent_v4beta1/event_service.rst | 6 + docs/talent_v4beta1/job_service.rst | 11 + docs/talent_v4beta1/profile_service.rst | 11 + docs/talent_v4beta1/services.rst | 30 +- docs/talent_v4beta1/tenant_service.rst | 11 + docs/talent_v4beta1/types.rst | 1 + google/cloud/talent_v4/__init__.py | 4 +- .../services/company_service/async_client.py | 64 ++- .../services/company_service/client.py | 78 ++-- .../services/company_service/pagers.py | 27 +- .../company_service/transports/base.py | 21 +- .../company_service/transports/grpc.py | 112 +++-- .../transports/grpc_asyncio.py | 120 +++--- .../services/completion/async_client.py | 36 +- .../talent_v4/services/completion/client.py | 44 +- .../services/completion/transports/base.py | 19 +- .../services/completion/transports/grpc.py | 112 +++-- .../completion/transports/grpc_asyncio.py | 120 +++--- .../services/event_service/async_client.py | 39 +- .../services/event_service/client.py | 50 ++- .../services/event_service/transports/base.py | 18 +- .../services/event_service/transports/grpc.py | 112 +++-- .../event_service/transports/grpc_asyncio.py | 120 +++--- .../services/job_service/async_client.py | 153 ++++--- .../talent_v4/services/job_service/client.py | 192 +++++---- .../talent_v4/services/job_service/pagers.py | 27 +- .../services/job_service/transports/base.py | 21 +- .../services/job_service/transports/grpc.py | 114 +++--- .../job_service/transports/grpc_asyncio.py | 122 +++--- .../services/tenant_service/async_client.py | 64 ++- .../services/tenant_service/client.py | 78 ++-- .../services/tenant_service/pagers.py | 27 +- .../tenant_service/transports/base.py | 21 +- .../tenant_service/transports/grpc.py | 112 +++-- .../tenant_service/transports/grpc_asyncio.py | 120 +++--- google/cloud/talent_v4/types/__init__.py | 96 ++--- google/cloud/talent_v4/types/common.py | 43 +- google/cloud/talent_v4/types/company.py | 6 +- .../cloud/talent_v4/types/company_service.py | 10 +- .../talent_v4/types/completion_service.py | 10 +- google/cloud/talent_v4/types/event.py | 6 +- google/cloud/talent_v4/types/event_service.py | 2 +- google/cloud/talent_v4/types/filters.py | 32 +- google/cloud/talent_v4/types/histogram.py | 2 +- google/cloud/talent_v4/types/job.py | 40 +- google/cloud/talent_v4/types/job_service.py | 62 +-- .../cloud/talent_v4/types/tenant_service.py | 10 +- .../application_service/async_client.py | 62 ++- .../services/application_service/client.py | 76 ++-- .../services/application_service/pagers.py | 27 +- .../application_service/transports/base.py | 21 +- .../application_service/transports/grpc.py | 112 +++-- .../transports/grpc_asyncio.py | 120 +++--- .../services/company_service/async_client.py | 61 ++- .../services/company_service/client.py | 75 ++-- .../services/company_service/pagers.py | 27 +- .../company_service/transports/base.py | 21 +- .../company_service/transports/grpc.py | 112 +++-- .../transports/grpc_asyncio.py | 120 +++--- .../services/completion/async_client.py | 36 +- .../services/completion/client.py | 44 +- .../services/completion/transports/base.py | 19 +- .../services/completion/transports/grpc.py | 112 +++-- .../completion/transports/grpc_asyncio.py | 120 +++--- .../services/event_service/async_client.py | 39 +- .../services/event_service/client.py | 50 ++- .../services/event_service/transports/base.py | 18 +- .../services/event_service/transports/grpc.py | 112 +++-- .../event_service/transports/grpc_asyncio.py | 120 +++--- .../services/job_service/async_client.py | 146 ++++--- .../services/job_service/client.py | 180 ++++---- .../services/job_service/pagers.py | 59 +-- .../services/job_service/transports/base.py | 21 +- .../services/job_service/transports/grpc.py | 114 +++--- .../job_service/transports/grpc_asyncio.py | 122 +++--- .../services/profile_service/async_client.py | 64 ++- .../services/profile_service/client.py | 78 ++-- .../services/profile_service/pagers.py | 43 +- .../profile_service/transports/base.py | 21 +- .../profile_service/transports/grpc.py | 112 +++-- .../transports/grpc_asyncio.py | 120 +++--- .../services/tenant_service/async_client.py | 61 ++- .../services/tenant_service/client.py | 75 ++-- .../services/tenant_service/pagers.py | 27 +- .../tenant_service/transports/base.py | 21 +- .../tenant_service/transports/grpc.py | 112 +++-- .../tenant_service/transports/grpc_asyncio.py | 120 +++--- google/cloud/talent_v4beta1/types/__init__.py | 252 ++++++------ .../cloud/talent_v4beta1/types/application.py | 18 +- .../types/application_service.py | 10 +- google/cloud/talent_v4beta1/types/common.py | 55 +-- google/cloud/talent_v4beta1/types/company.py | 6 +- .../talent_v4beta1/types/company_service.py | 10 +- .../types/completion_service.py | 10 +- google/cloud/talent_v4beta1/types/event.py | 10 +- .../talent_v4beta1/types/event_service.py | 2 +- google/cloud/talent_v4beta1/types/filters.py | 82 ++-- .../cloud/talent_v4beta1/types/histogram.py | 2 +- google/cloud/talent_v4beta1/types/job.py | 40 +- .../cloud/talent_v4beta1/types/job_service.py | 58 +-- google/cloud/talent_v4beta1/types/profile.py | 108 ++--- .../talent_v4beta1/types/profile_service.py | 28 +- google/cloud/talent_v4beta1/types/tenant.py | 2 +- .../talent_v4beta1/types/tenant_service.py | 10 +- noxfile.py | 59 ++- renovate.json | 3 +- samples/snippets/noxfile.py | 2 +- setup.py | 7 +- synth.metadata | 262 +----------- synth.py | 2 +- testing/constraints-3.6.txt | 5 +- tests/unit/gapic/talent_v4/__init__.py | 15 + .../gapic/talent_v4/test_company_service.py | 299 ++++++++++---- tests/unit/gapic/talent_v4/test_completion.py | 232 +++++++---- .../gapic/talent_v4/test_event_service.py | 237 +++++++---- .../unit/gapic/talent_v4/test_job_service.py | 384 ++++++++++++++---- .../gapic/talent_v4/test_tenant_service.py | 299 ++++++++++---- tests/unit/gapic/talent_v4beta1/__init__.py | 15 + .../test_application_service.py | 309 ++++++++++---- .../talent_v4beta1/test_company_service.py | 299 ++++++++++---- .../gapic/talent_v4beta1/test_completion.py | 232 +++++++---- .../talent_v4beta1/test_event_service.py | 237 +++++++---- .../gapic/talent_v4beta1/test_job_service.py | 384 ++++++++++++++---- .../talent_v4beta1/test_profile_service.py | 315 ++++++++++---- .../talent_v4beta1/test_tenant_service.py | 299 ++++++++++---- 151 files changed, 6267 insertions(+), 4345 deletions(-) create mode 100644 .github/header-checker-lint.yml create mode 100644 .kokoro/samples/python3.6/periodic-head.cfg create mode 100644 .kokoro/samples/python3.7/periodic-head.cfg create mode 100644 .kokoro/samples/python3.8/periodic-head.cfg create mode 100755 .kokoro/test-samples-against-head.sh create mode 100755 .kokoro/test-samples-impl.sh create mode 100644 docs/talent_v4/company_service.rst create mode 100644 docs/talent_v4/completion.rst create mode 100644 docs/talent_v4/event_service.rst create mode 100644 docs/talent_v4/job_service.rst create mode 100644 docs/talent_v4/tenant_service.rst create mode 100644 docs/talent_v4beta1/application_service.rst create mode 100644 docs/talent_v4beta1/company_service.rst create mode 100644 docs/talent_v4beta1/completion.rst create mode 100644 docs/talent_v4beta1/event_service.rst create mode 100644 docs/talent_v4beta1/job_service.rst create mode 100644 docs/talent_v4beta1/profile_service.rst create mode 100644 docs/talent_v4beta1/tenant_service.rst diff --git a/.coveragerc b/.coveragerc index dd39c854..8a9e352c 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,35 +1,18 @@ -# -*- 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/header-checker-lint.yml b/.github/header-checker-lint.yml new file mode 100644 index 00000000..fc281c05 --- /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"], + "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/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/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..32302e48 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,6 +12,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.4 + rev: 3.9.0 hooks: - id: flake8 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/CONTRIBUTING.rst b/CONTRIBUTING.rst index 12046067..89f4d56d 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -70,9 +70,14 @@ We use `nox `__ to instrument our tests. - To test your changes, run unit tests with ``nox``:: $ nox -s unit-2.7 - $ nox -s unit-3.7 + $ nox -s unit-3.8 $ ... +- Args to pytest can be passed through the nox command separated by a `--`. For + example, to run a single test:: + + $ nox -s unit-3.8 -- -k + .. note:: The unit tests and system tests are described in the @@ -93,8 +98,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,13 +142,18 @@ Running System Tests - To run system tests, you can execute:: - $ nox -s system-3.7 + # Run all system tests + $ nox -s system-3.8 $ nox -s system-2.7 + # 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 + 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 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/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/talent_v4/company_service.rst b/docs/talent_v4/company_service.rst new file mode 100644 index 00000000..f850f370 --- /dev/null +++ b/docs/talent_v4/company_service.rst @@ -0,0 +1,11 @@ +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..28d73f01 --- /dev/null +++ b/docs/talent_v4/job_service.rst @@ -0,0 +1,11 @@ +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..d38c6bcd --- /dev/null +++ b/docs/talent_v4/tenant_service.rst @@ -0,0 +1,11 @@ +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..6539e8fd --- /dev/null +++ b/docs/talent_v4beta1/application_service.rst @@ -0,0 +1,11 @@ +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..e2050c75 --- /dev/null +++ b/docs/talent_v4beta1/company_service.rst @@ -0,0 +1,11 @@ +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..a78f4f32 --- /dev/null +++ b/docs/talent_v4beta1/job_service.rst @@ -0,0 +1,11 @@ +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..e558ed06 --- /dev/null +++ b/docs/talent_v4beta1/profile_service.rst @@ -0,0 +1,11 @@ +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..4de1dcfe --- /dev/null +++ b/docs/talent_v4beta1/tenant_service.rst @@ -0,0 +1,11 @@ +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_v4/__init__.py b/google/cloud/talent_v4/__init__.py index 1d4b845e..b193e4de 100644 --- a/google/cloud/talent_v4/__init__.py +++ b/google/cloud/talent_v4/__init__.py @@ -127,6 +127,7 @@ "JobLevel", "JobQuery", "JobResult", + "JobServiceClient", "JobView", "ListCompaniesRequest", "ListCompaniesResponse", @@ -143,11 +144,10 @@ "SearchJobsResponse", "SpellingCorrection", "Tenant", - "TenantServiceClient", "TimestampRange", "UpdateCompanyRequest", "UpdateJobRequest", "UpdateTenantRequest", "Visibility", - "JobServiceClient", + "TenantServiceClient", ) 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..dbb65fa2 100644 --- a/google/cloud/talent_v4/services/company_service/async_client.py +++ b/google/cloud/talent_v4/services/company_service/async_client.py @@ -84,7 +84,36 @@ class CompanyServiceAsyncClient: 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 @@ -161,7 +190,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,10 +200,11 @@ 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 @@ -187,7 +217,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, @@ -248,7 +278,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,6 +289,7 @@ 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. @@ -270,7 +301,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, @@ -308,6 +339,7 @@ async def get_company( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -338,17 +370,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,6 +393,7 @@ 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. @@ -371,7 +405,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, @@ -436,7 +470,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,6 +479,7 @@ 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. @@ -484,6 +519,7 @@ async def delete_company( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -512,7 +548,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,6 +558,7 @@ 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. @@ -533,7 +570,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 @@ -569,6 +606,7 @@ async def list_companies( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, 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..10f6d998 100644 --- a/google/cloud/talent_v4/services/company_service/client.py +++ b/google/cloud/talent_v4/services/company_service/client.py @@ -116,6 +116,22 @@ 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 @@ -128,7 +144,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -345,7 +357,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,20 +375,21 @@ 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 @@ -389,7 +402,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, @@ -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,6 +475,7 @@ 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. @@ -473,7 +487,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, @@ -534,17 +548,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,6 +571,7 @@ 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. @@ -567,7 +583,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, @@ -633,15 +649,16 @@ 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. @@ -702,16 +719,17 @@ 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. @@ -723,7 +741,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 diff --git a/google/cloud/talent_v4/services/company_service/pagers.py b/google/cloud/talent_v4/services/company_service/pagers.py index 992c4b53..beac2a8b 100644 --- a/google/cloud/talent_v4/services/company_service/pagers.py +++ b/google/cloud/talent_v4/services/company_service/pagers.py @@ -15,7 +15,16 @@ # 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 +34,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 +43,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 +61,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 +96,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 +105,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. """ @@ -114,9 +123,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. 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..ccaaff88 100644 --- a/google/cloud/talent_v4/services/company_service/transports/base.py +++ b/google/cloud/talent_v4/services/company_service/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -122,6 +122,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -138,6 +139,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -151,6 +153,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..fe1e7dd2 100644 --- a/google/cloud/talent_v4/services/company_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/company_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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, ) -> None: @@ -91,6 +92,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): @@ -105,72 +110,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, + ) - # 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,17 +171,8 @@ 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( @@ -202,7 +186,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 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..0643fff5 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 @@ -65,7 +65,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 @@ -105,6 +105,7 @@ def __init__( 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, ) -> None: @@ -136,12 +137,16 @@ 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. Raises: @@ -150,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" - ) + 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, + ) - # 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 +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/completion/async_client.py b/google/cloud/talent_v4/services/completion/async_client.py index 2c91e861..16c1c698 100644 --- a/google/cloud/talent_v4/services/completion/async_client.py +++ b/google/cloud/talent_v4/services/completion/async_client.py @@ -72,7 +72,36 @@ class CompletionAsyncClient: 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 @@ -149,7 +178,7 @@ 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, @@ -159,7 +188,7 @@ 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. @@ -177,6 +206,7 @@ async def complete_query( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, 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..6eacd4ca 100644 --- a/google/cloud/talent_v4/services/completion/client.py +++ b/google/cloud/talent_v4/services/completion/client.py @@ -108,6 +108,22 @@ 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 @@ -120,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. + CompletionClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -337,7 +349,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,7 +367,7 @@ 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, @@ -365,7 +377,7 @@ 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. diff --git a/google/cloud/talent_v4/services/completion/transports/base.py b/google/cloud/talent_v4/services/completion/transports/base.py index efb1e327..e8fdb64a 100644 --- a/google/cloud/talent_v4/services/completion/transports/base.py +++ b/google/cloud/talent_v4/services/completion/transports/base.py @@ -70,10 +70,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -81,6 +81,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -90,20 +93,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,6 +116,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, diff --git a/google/cloud/talent_v4/services/completion/transports/grpc.py b/google/cloud/talent_v4/services/completion/transports/grpc.py index 08fe29d3..7732a1dc 100644 --- a/google/cloud/talent_v4/services/completion/transports/grpc.py +++ b/google/cloud/talent_v4/services/completion/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( 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, ) -> None: @@ -87,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): @@ -101,72 +106,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 - - # 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, + ) - # 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,17 +167,8 @@ 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( @@ -198,7 +182,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 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..d23bd831 100644 --- a/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py +++ b/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py @@ -61,7 +61,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 @@ -101,6 +101,7 @@ def __init__( 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, ) -> None: @@ -132,12 +133,16 @@ 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. Raises: @@ -146,72 +151,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 - - # 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, + ) - # 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 +212,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/async_client.py b/google/cloud/talent_v4/services/event_service/async_client.py index 8a6a6e41..c6237025 100644 --- a/google/cloud/talent_v4/services/event_service/async_client.py +++ b/google/cloud/talent_v4/services/event_service/async_client.py @@ -73,7 +73,36 @@ class EventServiceAsyncClient: 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 @@ -156,7 +185,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,13 +194,15 @@ 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. @@ -183,7 +214,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. diff --git a/google/cloud/talent_v4/services/event_service/client.py b/google/cloud/talent_v4/services/event_service/client.py index 06f1fd4f..9cae6703 100644 --- a/google/cloud/talent_v4/services/event_service/client.py +++ b/google/cloud/talent_v4/services/event_service/client.py @@ -109,6 +109,22 @@ 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 @@ -121,7 +137,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -322,7 +334,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,22 +358,24 @@ 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. @@ -373,7 +387,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. 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..5f0f004d 100644 --- a/google/cloud/talent_v4/services/event_service/transports/base.py +++ b/google/cloud/talent_v4/services/event_service/transports/base.py @@ -71,10 +71,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -82,6 +82,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -91,20 +94,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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..05c80ebc 100644 --- a/google/cloud/talent_v4/services/event_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/event_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( 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, ) -> None: @@ -88,6 +89,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): @@ -102,72 +107,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 - - # 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, + ) - # 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,17 +168,8 @@ 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( @@ -199,7 +183,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 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..302f0083 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 @@ -62,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 @@ -102,6 +102,7 @@ def __init__( 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, ) -> None: @@ -133,12 +134,16 @@ 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. Raises: @@ -147,72 +152,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 - - # 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, + ) - # 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 +213,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/async_client.py b/google/cloud/talent_v4/services/job_service/async_client.py index ec420503..06bee535 100644 --- a/google/cloud/talent_v4/services/job_service/async_client.py +++ b/google/cloud/talent_v4/services/job_service/async_client.py @@ -84,7 +84,36 @@ class JobServiceAsyncClient: 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 @@ -163,7 +192,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,10 +201,11 @@ 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 @@ -188,11 +218,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. @@ -248,7 +278,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,13 +287,15 @@ 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. @@ -275,16 +307,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. @@ -349,7 +378,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,6 +386,7 @@ 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. @@ -368,11 +398,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. @@ -404,6 +434,7 @@ async def get_job( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -437,14 +468,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,6 +487,7 @@ 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. @@ -467,11 +499,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. @@ -527,7 +559,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,13 +568,15 @@ 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. @@ -554,16 +588,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. @@ -629,7 +660,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,6 +668,7 @@ 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. @@ -676,6 +708,7 @@ async def delete_job( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -705,7 +738,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 +750,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,6 +762,7 @@ 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. @@ -739,16 +774,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. @@ -813,7 +845,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 +854,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,7 +880,8 @@ 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. @@ -859,7 +893,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 @@ -897,6 +931,7 @@ async def list_jobs( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -937,7 +972,7 @@ 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. @@ -948,7 +983,7 @@ 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. @@ -998,7 +1033,7 @@ 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. @@ -1009,7 +1044,7 @@ 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. diff --git a/google/cloud/talent_v4/services/job_service/client.py b/google/cloud/talent_v4/services/job_service/client.py index 0e8ec2b0..8a43c082 100644 --- a/google/cloud/talent_v4/services/job_service/client.py +++ b/google/cloud/talent_v4/services/job_service/client.py @@ -118,6 +118,22 @@ 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 @@ -130,7 +146,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -363,7 +375,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,19 +395,20 @@ 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 @@ -408,11 +421,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. @@ -469,22 +482,24 @@ 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. @@ -496,16 +511,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. @@ -530,9 +542,8 @@ def batch_create_jobs( 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,14 +582,15 @@ 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. @@ -590,11 +602,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. @@ -652,14 +664,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,6 +683,7 @@ 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. @@ -682,11 +695,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. @@ -743,22 +756,24 @@ 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. @@ -770,16 +785,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. @@ -804,9 +816,8 @@ def batch_update_jobs( 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,14 +857,15 @@ 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. @@ -915,9 +927,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 +939,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,6 +951,7 @@ 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. @@ -949,16 +963,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. @@ -983,9 +994,8 @@ def batch_delete_jobs( 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 +1034,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,7 +1069,8 @@ 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. @@ -1070,7 +1082,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 @@ -1141,7 +1153,7 @@ 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. @@ -1152,7 +1164,7 @@ 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. @@ -1203,7 +1215,7 @@ 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. @@ -1214,7 +1226,7 @@ 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. diff --git a/google/cloud/talent_v4/services/job_service/pagers.py b/google/cloud/talent_v4/services/job_service/pagers.py index e759d8e3..bbef2c82 100644 --- a/google/cloud/talent_v4/services/job_service/pagers.py +++ b/google/cloud/talent_v4/services/job_service/pagers.py @@ -15,7 +15,16 @@ # 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 +34,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 +43,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 +61,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 +96,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 +105,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. """ @@ -114,9 +123,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. 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..97429e5b 100644 --- a/google/cloud/talent_v4/services/job_service/transports/base.py +++ b/google/cloud/talent_v4/services/job_service/transports/base.py @@ -75,10 +75,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -86,6 +86,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -95,20 +98,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -127,6 +127,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -146,6 +147,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -162,6 +164,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..d80e73f4 100644 --- a/google/cloud/talent_v4/services/job_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/job_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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, ) -> None: @@ -93,6 +94,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): @@ -107,72 +112,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 + 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, + ) - # 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,18 +174,8 @@ 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( @@ -205,7 +189,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 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..599527c8 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 @@ -67,7 +67,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 @@ -107,6 +107,7 @@ def __init__( 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, ) -> None: @@ -138,12 +139,16 @@ 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. Raises: @@ -152,72 +157,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 + 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, + ) - # 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 +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 = {} - 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: 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..51ebcab7 100644 --- a/google/cloud/talent_v4/services/tenant_service/async_client.py +++ b/google/cloud/talent_v4/services/tenant_service/async_client.py @@ -81,7 +81,36 @@ class TenantServiceAsyncClient: 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 @@ -158,7 +187,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,10 +196,11 @@ 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 @@ -183,7 +213,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 @@ -245,7 +275,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,6 +285,7 @@ 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. @@ -266,7 +297,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 @@ -305,6 +336,7 @@ async def get_tenant( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -335,17 +367,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,6 +390,7 @@ 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. @@ -368,7 +402,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 @@ -432,7 +466,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,6 +474,7 @@ 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. @@ -479,6 +514,7 @@ async def delete_tenant( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -507,7 +543,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,6 +552,7 @@ 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. @@ -527,7 +564,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 @@ -563,6 +600,7 @@ async def list_tenants( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, 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..ef6d560c 100644 --- a/google/cloud/talent_v4/services/tenant_service/client.py +++ b/google/cloud/talent_v4/services/tenant_service/client.py @@ -113,6 +113,22 @@ 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 @@ -125,7 +141,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -326,7 +338,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,19 +356,20 @@ 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 @@ -369,7 +382,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 @@ -432,16 +445,17 @@ 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. @@ -453,7 +467,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 @@ -515,17 +529,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,6 +552,7 @@ 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. @@ -548,7 +564,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 @@ -613,14 +629,15 @@ 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. @@ -681,15 +698,16 @@ 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. @@ -701,7 +719,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 diff --git a/google/cloud/talent_v4/services/tenant_service/pagers.py b/google/cloud/talent_v4/services/tenant_service/pagers.py index d671fdb7..91d4a213 100644 --- a/google/cloud/talent_v4/services/tenant_service/pagers.py +++ b/google/cloud/talent_v4/services/tenant_service/pagers.py @@ -15,7 +15,16 @@ # 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 +34,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 +43,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 +61,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 +96,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 +105,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. """ @@ -114,9 +123,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. 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..c921d237 100644 --- a/google/cloud/talent_v4/services/tenant_service/transports/base.py +++ b/google/cloud/talent_v4/services/tenant_service/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -122,6 +122,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -138,6 +139,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -151,6 +153,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..d837f65e 100644 --- a/google/cloud/talent_v4/services/tenant_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/tenant_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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, ) -> None: @@ -91,6 +92,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): @@ -105,72 +110,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, + ) - # 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,17 +171,8 @@ 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( @@ -202,7 +186,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 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..072a50dc 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 @@ -65,7 +65,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 @@ -105,6 +105,7 @@ def __init__( 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, ) -> None: @@ -136,12 +137,16 @@ 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. Raises: @@ -150,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" - ) + 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, + ) - # 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 +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/types/__init__.py b/google/cloud/talent_v4/types/__init__.py index faf71c78..29719f84 100644 --- a/google/cloud/talent_v4/types/__init__.py +++ b/google/cloud/talent_v4/types/__init__.py @@ -16,34 +16,34 @@ # 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 +55,10 @@ ) from .event_service import CreateClientEventRequest from .filters import ( + CommuteFilter, + CompensationFilter, JobQuery, LocationFilter, - CompensationFilter, - CommuteFilter, ) from .histogram import ( HistogramQuery, @@ -66,93 +66,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..6acd7469 100644 --- a/google/cloud/talent_v4/types/common.py +++ b/google/cloud/talent_v4/types/common.py @@ -178,6 +178,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 @@ -206,9 +207,9 @@ 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). """ @@ -222,7 +223,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 +231,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): @@ -342,7 +343,7 @@ 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. """ @@ -378,7 +379,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 @@ -495,14 +496,14 @@ 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 +513,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 +595,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] @@ -656,12 +657,12 @@ 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 @@ -689,7 +690,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 +702,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``. diff --git a/google/cloud/talent_v4/types/company.py b/google/cloud/talent_v4/types/company.py index 9955928e..84df7fe7 100644 --- a/google/cloud/talent_v4/types/company.py +++ b/google/cloud/talent_v4/types/company.py @@ -48,7 +48,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 +87,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): @@ -101,7 +101,7 @@ 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] diff --git a/google/cloud/talent_v4/types/company_service.py b/google/cloud/talent_v4/types/company_service.py index 0e166ef9..c6862175 100644 --- a/google/cloud/talent_v4/types/company_service.py +++ b/google/cloud/talent_v4/types/company_service.py @@ -46,7 +46,7 @@ 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. """ @@ -75,10 +75,10 @@ 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 @@ -153,11 +153,11 @@ 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. """ diff --git a/google/cloud/talent_v4/types/completion_service.py b/google/cloud/talent_v4/types/completion_service.py index ba2529b2..fe233356 100644 --- a/google/cloud/talent_v4/types/completion_service.py +++ b/google/cloud/talent_v4/types/completion_service.py @@ -57,10 +57,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]. """ @@ -97,10 +97,10 @@ 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. """ @@ -111,7 +111,7 @@ class CompletionResult(proto.Message): 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 diff --git a/google/cloud/talent_v4/types/event.py b/google/cloud/talent_v4/types/event.py index 8ecb3a87..40ffe6f2 100644 --- a/google/cloud/talent_v4/types/event.py +++ b/google/cloud/talent_v4/types/event.py @@ -44,9 +44,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. @@ -72,7 +72,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]): diff --git a/google/cloud/talent_v4/types/event_service.py b/google/cloud/talent_v4/types/event_service.py index 264d2f2d..8a328f9a 100644 --- a/google/cloud/talent_v4/types/event_service.py +++ b/google/cloud/talent_v4/types/event_service.py @@ -36,7 +36,7 @@ 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. diff --git a/google/cloud/talent_v4/types/filters.py b/google/cloud/talent_v4/types/filters.py index 62a8aa57..482632fa 100644 --- a/google/cloud/talent_v4/types/filters.py +++ b/google/cloud/talent_v4/types/filters.py @@ -65,7 +65,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 +83,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 +94,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 +118,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 +157,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 +180,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]): @@ -246,7 +246,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 +255,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. @@ -304,12 +304,12 @@ 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 @@ -341,13 +341,13 @@ 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 +357,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 diff --git a/google/cloud/talent_v4/types/histogram.py b/google/cloud/talent_v4/types/histogram.py index ac6443df..ec9484c9 100644 --- a/google/cloud/talent_v4/types/histogram.py +++ b/google/cloud/talent_v4/types/histogram.py @@ -48,7 +48,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. diff --git a/google/cloud/talent_v4/types/job.py b/google/cloud/talent_v4/types/job.py index f1320f94..2bd27c59 100644 --- a/google/cloud/talent_v4/types/job.py +++ b/google/cloud/talent_v4/types/job.py @@ -111,15 +111,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 +134,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 +142,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 +167,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 +200,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 +215,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 +223,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,19 +295,19 @@ 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. """ @@ -347,7 +347,7 @@ 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 +355,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]. @@ -376,7 +376,7 @@ class ProcessingOptions(proto.Message): 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: diff --git a/google/cloud/talent_v4/types/job_service.py b/google/cloud/talent_v4/types/job_service.py index 4b53ed10..78289bbe 100644 --- a/google/cloud/talent_v4/types/job_service.py +++ b/google/cloud/talent_v4/types/job_service.py @@ -74,7 +74,7 @@ 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. """ @@ -102,9 +102,9 @@ 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 @@ -182,7 +182,7 @@ 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] @@ -204,13 +204,13 @@ 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. """ @@ -235,17 +235,17 @@ class SearchJobsRequest(proto.Message): 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 +255,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 +368,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 +458,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 +470,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 +528,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. @@ -623,17 +623,17 @@ 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 +644,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 +659,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 +668,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,7 +687,7 @@ 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]. """ @@ -708,10 +708,10 @@ 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 @@ -762,7 +762,7 @@ 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. """ @@ -782,10 +782,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. @@ -848,7 +848,7 @@ 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,7 +858,7 @@ 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. @@ -877,7 +877,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 +894,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 +911,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_service.py b/google/cloud/talent_v4/types/tenant_service.py index 2f77b0d1..be5e4d8d 100644 --- a/google/cloud/talent_v4/types/tenant_service.py +++ b/google/cloud/talent_v4/types/tenant_service.py @@ -46,7 +46,7 @@ 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. """ @@ -73,10 +73,10 @@ 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 @@ -139,11 +139,11 @@ 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. """ 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..6c6bb683 100644 --- a/google/cloud/talent_v4beta1/services/application_service/async_client.py +++ b/google/cloud/talent_v4beta1/services/application_service/async_client.py @@ -92,7 +92,36 @@ class ApplicationServiceAsyncClient: 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 @@ -170,7 +199,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,12 +209,14 @@ 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. @@ -197,7 +228,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. @@ -254,7 +285,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,6 +296,7 @@ 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. @@ -276,7 +308,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. @@ -310,6 +342,7 @@ async def get_application( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -339,13 +372,14 @@ 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. @@ -357,7 +391,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. @@ -414,7 +448,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,6 +458,7 @@ 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. @@ -463,6 +498,7 @@ async def delete_application( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -491,7 +527,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,6 +537,7 @@ 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. @@ -512,7 +549,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 @@ -549,6 +586,7 @@ async def list_applications( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, 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..f93ebd01 100644 --- a/google/cloud/talent_v4beta1/services/application_service/client.py +++ b/google/cloud/talent_v4beta1/services/application_service/client.py @@ -120,6 +120,22 @@ 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 @@ -132,7 +148,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -386,7 +398,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,22 +416,24 @@ 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. @@ -431,7 +445,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. @@ -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,6 +514,7 @@ 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. @@ -511,7 +526,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. @@ -567,13 +582,14 @@ 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. @@ -585,7 +601,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. @@ -643,9 +659,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,6 +669,7 @@ 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. @@ -713,16 +730,17 @@ 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. @@ -734,7 +752,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 diff --git a/google/cloud/talent_v4beta1/services/application_service/pagers.py b/google/cloud/talent_v4beta1/services/application_service/pagers.py index 0525dae8..1aa9124c 100644 --- a/google/cloud/talent_v4beta1/services/application_service/pagers.py +++ b/google/cloud/talent_v4beta1/services/application_service/pagers.py @@ -15,7 +15,16 @@ # 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 +34,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 +43,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 +61,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 +96,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 +105,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. """ @@ -114,9 +123,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. 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..9667920d 100644 --- a/google/cloud/talent_v4beta1/services/application_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/application_service/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -122,6 +122,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -138,6 +139,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -151,6 +153,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..e47f721b 100644 --- a/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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, ) -> None: @@ -91,6 +92,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): @@ -105,72 +110,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, + ) - # 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,17 +171,8 @@ 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( @@ -202,7 +186,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 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..95164149 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 @@ -65,7 +65,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 @@ -105,6 +105,7 @@ def __init__( 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, ) -> None: @@ -136,12 +137,16 @@ 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. Raises: @@ -150,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" - ) + 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, + ) - # 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 +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/company_service/async_client.py b/google/cloud/talent_v4beta1/services/company_service/async_client.py index 98c39a8e..30a4dfff 100644 --- a/google/cloud/talent_v4beta1/services/company_service/async_client.py +++ b/google/cloud/talent_v4beta1/services/company_service/async_client.py @@ -81,7 +81,36 @@ class CompanyServiceAsyncClient: 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 @@ -158,7 +187,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,10 +199,11 @@ 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 @@ -186,7 +216,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, @@ -247,7 +277,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,6 +291,7 @@ 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. @@ -272,7 +303,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, @@ -310,6 +341,7 @@ async def get_company( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -339,13 +371,14 @@ 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. @@ -357,7 +390,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, @@ -420,7 +453,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,6 +465,7 @@ 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. @@ -471,6 +505,7 @@ async def delete_company( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -499,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_v4beta1.types.ListCompaniesRequest`): The request object. List companies for which the client has ACL visibility. parent (:class:`str`): @@ -512,6 +547,7 @@ 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. @@ -523,7 +559,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 @@ -559,6 +595,7 @@ async def list_companies( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, 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..aa2572b5 100644 --- a/google/cloud/talent_v4beta1/services/company_service/client.py +++ b/google/cloud/talent_v4beta1/services/company_service/client.py @@ -115,6 +115,22 @@ 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 @@ -127,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -331,7 +343,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 +361,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,10 +373,11 @@ 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 @@ -377,7 +390,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, @@ -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,6 +466,7 @@ 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. @@ -464,7 +478,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, @@ -524,13 +538,14 @@ 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. @@ -542,7 +557,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, @@ -606,9 +621,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,6 +633,7 @@ 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. @@ -678,10 +694,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,6 +707,7 @@ 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. @@ -702,7 +719,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 diff --git a/google/cloud/talent_v4beta1/services/company_service/pagers.py b/google/cloud/talent_v4beta1/services/company_service/pagers.py index 6b25c9a9..cb04a126 100644 --- a/google/cloud/talent_v4beta1/services/company_service/pagers.py +++ b/google/cloud/talent_v4beta1/services/company_service/pagers.py @@ -15,7 +15,16 @@ # 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 +34,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 +43,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 +61,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 +96,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 +105,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. """ @@ -114,9 +123,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. 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..e4af061a 100644 --- a/google/cloud/talent_v4beta1/services/company_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/company_service/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -122,6 +122,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -138,6 +139,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -151,6 +153,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..b1d479f5 100644 --- a/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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, ) -> None: @@ -91,6 +92,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): @@ -105,72 +110,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, + ) - # 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,17 +171,8 @@ 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( @@ -202,7 +186,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 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..70bdce4b 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 @@ -65,7 +65,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 @@ -105,6 +105,7 @@ def __init__( 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, ) -> None: @@ -136,12 +137,16 @@ 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. Raises: @@ -150,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" - ) + 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, + ) - # 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 +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/completion/async_client.py b/google/cloud/talent_v4beta1/services/completion/async_client.py index 40da92eb..194a7b7e 100644 --- a/google/cloud/talent_v4beta1/services/completion/async_client.py +++ b/google/cloud/talent_v4beta1/services/completion/async_client.py @@ -70,7 +70,36 @@ class CompletionAsyncClient: 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 @@ -147,7 +176,7 @@ 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, @@ -157,7 +186,7 @@ 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. @@ -175,6 +204,7 @@ async def complete_query( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, 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..780d7342 100644 --- a/google/cloud/talent_v4beta1/services/completion/client.py +++ b/google/cloud/talent_v4beta1/services/completion/client.py @@ -108,6 +108,22 @@ 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 @@ -120,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. + CompletionClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -324,7 +336,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,7 +354,7 @@ 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, @@ -352,7 +364,7 @@ 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. diff --git a/google/cloud/talent_v4beta1/services/completion/transports/base.py b/google/cloud/talent_v4beta1/services/completion/transports/base.py index 95e41990..fb7aaee0 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/base.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/base.py @@ -70,10 +70,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -81,6 +81,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -90,20 +93,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,6 +116,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, diff --git a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py index 086da12a..164a4e5d 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( 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, ) -> None: @@ -87,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): @@ -101,72 +106,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 - - # 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, + ) - # 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,17 +167,8 @@ 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( @@ -198,7 +182,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 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..88a6a731 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py @@ -61,7 +61,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 @@ -101,6 +101,7 @@ def __init__( 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, ) -> None: @@ -132,12 +133,16 @@ 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. Raises: @@ -146,72 +151,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 - - # 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, + ) - # 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 +212,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/async_client.py b/google/cloud/talent_v4beta1/services/event_service/async_client.py index 553aed17..4bddf1e1 100644 --- a/google/cloud/talent_v4beta1/services/event_service/async_client.py +++ b/google/cloud/talent_v4beta1/services/event_service/async_client.py @@ -73,7 +73,36 @@ class EventServiceAsyncClient: 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 @@ -156,7 +185,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,13 +196,15 @@ 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. @@ -185,7 +216,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. diff --git a/google/cloud/talent_v4beta1/services/event_service/client.py b/google/cloud/talent_v4beta1/services/event_service/client.py index 21204729..b231a98d 100644 --- a/google/cloud/talent_v4beta1/services/event_service/client.py +++ b/google/cloud/talent_v4beta1/services/event_service/client.py @@ -109,6 +109,22 @@ 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 @@ -121,7 +137,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -325,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, ) @@ -349,9 +361,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,13 +372,15 @@ 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. @@ -378,7 +392,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. 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..0fdd167b 100644 --- a/google/cloud/talent_v4beta1/services/event_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/event_service/transports/base.py @@ -71,10 +71,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -82,6 +82,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -91,20 +94,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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..18186207 100644 --- a/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( 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, ) -> None: @@ -88,6 +89,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): @@ -102,72 +107,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 - - # 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, + ) - # 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,17 +168,8 @@ 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( @@ -199,7 +183,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 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..687b2763 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 @@ -62,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 @@ -102,6 +102,7 @@ def __init__( 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, ) -> None: @@ -133,12 +134,16 @@ 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. Raises: @@ -147,72 +152,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 - - # 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, + ) - # 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 +213,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/async_client.py b/google/cloud/talent_v4beta1/services/job_service/async_client.py index a5ad40c6..9f758a33 100644 --- a/google/cloud/talent_v4beta1/services/job_service/async_client.py +++ b/google/cloud/talent_v4beta1/services/job_service/async_client.py @@ -80,7 +80,36 @@ class JobServiceAsyncClient: 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 @@ -159,7 +188,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,10 +199,11 @@ 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 @@ -186,12 +216,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. @@ -247,7 +276,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,10 +287,11 @@ 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 @@ -274,18 +304,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. @@ -350,7 +376,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,6 +387,7 @@ 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. @@ -372,12 +399,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. @@ -409,6 +435,7 @@ async def get_job( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -441,9 +468,9 @@ 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 @@ -456,12 +483,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. @@ -515,7 +541,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,10 +552,11 @@ 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 @@ -542,18 +569,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. @@ -619,7 +642,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,6 +653,7 @@ 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. @@ -669,6 +693,7 @@ async def delete_job( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -699,7 +724,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 +735,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,7 +751,8 @@ 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. @@ -788,7 +815,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 +826,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,7 +852,8 @@ 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. @@ -836,7 +865,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 @@ -874,6 +903,7 @@ async def list_jobs( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -914,7 +944,7 @@ 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. @@ -925,7 +955,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 @@ -985,7 +1015,7 @@ 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. @@ -996,7 +1026,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 diff --git a/google/cloud/talent_v4beta1/services/job_service/client.py b/google/cloud/talent_v4beta1/services/job_service/client.py index 726b75ae..d044dc14 100644 --- a/google/cloud/talent_v4beta1/services/job_service/client.py +++ b/google/cloud/talent_v4beta1/services/job_service/client.py @@ -116,6 +116,22 @@ 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 @@ -128,7 +144,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -348,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, ) @@ -368,9 +380,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,10 +391,11 @@ 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 @@ -395,12 +408,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. @@ -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,10 +480,11 @@ 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 @@ -484,18 +497,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. @@ -520,9 +529,8 @@ def batch_create_jobs( 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 +569,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,6 +580,7 @@ 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. @@ -583,12 +592,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. @@ -645,9 +653,9 @@ 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 @@ -660,12 +668,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. @@ -720,9 +727,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,10 +738,11 @@ 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 @@ -747,18 +755,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. @@ -783,9 +787,8 @@ def batch_update_jobs( 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 +828,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,6 +839,7 @@ 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. @@ -898,9 +902,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 +913,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,7 +929,8 @@ 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. @@ -988,9 +994,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 +1005,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,7 +1031,8 @@ 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. @@ -1036,7 +1044,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 @@ -1107,7 +1115,7 @@ 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. @@ -1118,7 +1126,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 @@ -1179,7 +1187,7 @@ 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. @@ -1190,7 +1198,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 diff --git a/google/cloud/talent_v4beta1/services/job_service/pagers.py b/google/cloud/talent_v4beta1/services/job_service/pagers.py index fcefff46..47d07398 100644 --- a/google/cloud/talent_v4beta1/services/job_service/pagers.py +++ b/google/cloud/talent_v4beta1/services/job_service/pagers.py @@ -15,7 +15,16 @@ # 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 +34,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 +43,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 +61,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 +96,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 +105,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. """ @@ -114,9 +123,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. @@ -153,7 +162,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 +171,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 +189,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 +224,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 +233,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. """ @@ -242,9 +251,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. @@ -281,7 +290,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 +299,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 +317,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 +352,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 +361,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. """ @@ -370,9 +379,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. 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..5cb1997b 100644 --- a/google/cloud/talent_v4beta1/services/job_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/job_service/transports/base.py @@ -75,10 +75,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -86,6 +86,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -95,20 +98,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -127,6 +127,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -146,6 +147,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -162,6 +164,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..188b42a6 100644 --- a/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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, ) -> None: @@ -93,6 +94,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): @@ -107,72 +112,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 + 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, + ) - # 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,18 +174,8 @@ 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( @@ -205,7 +189,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 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..4896073b 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 @@ -67,7 +67,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 @@ -107,6 +107,7 @@ def __init__( 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, ) -> None: @@ -138,12 +139,16 @@ 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. Raises: @@ -152,72 +157,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 + 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, + ) - # 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 +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 = {} - 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: 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..7c581cb8 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/async_client.py +++ b/google/cloud/talent_v4beta1/services/profile_service/async_client.py @@ -86,7 +86,36 @@ class ProfileServiceAsyncClient: 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 @@ -162,7 +191,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,6 +200,7 @@ 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. @@ -182,7 +212,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 @@ -218,6 +248,7 @@ async def list_profiles( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -254,7 +285,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,10 +294,11 @@ 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 @@ -279,7 +311,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 @@ -338,7 +370,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,6 +378,7 @@ 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. @@ -357,7 +390,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 @@ -393,6 +426,7 @@ async def get_profile( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -423,9 +457,9 @@ 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 @@ -438,7 +472,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 @@ -499,7 +533,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,6 +541,7 @@ 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. @@ -546,6 +581,7 @@ async def delete_profile( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -581,7 +617,7 @@ 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. @@ -592,7 +628,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 diff --git a/google/cloud/talent_v4beta1/services/profile_service/client.py b/google/cloud/talent_v4beta1/services/profile_service/client.py index 4cef4bba..eb27801d 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/client.py +++ b/google/cloud/talent_v4beta1/services/profile_service/client.py @@ -118,6 +118,22 @@ 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 @@ -130,7 +146,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -347,7 +359,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,15 +376,16 @@ 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. @@ -384,7 +397,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 @@ -449,19 +462,20 @@ 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 @@ -474,7 +488,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 @@ -534,14 +548,15 @@ 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. @@ -553,7 +568,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 @@ -612,9 +627,9 @@ 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 @@ -627,7 +642,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 @@ -689,14 +704,15 @@ 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. @@ -764,7 +780,7 @@ 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. @@ -775,7 +791,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 diff --git a/google/cloud/talent_v4beta1/services/profile_service/pagers.py b/google/cloud/talent_v4beta1/services/profile_service/pagers.py index c2f71326..1793730e 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/pagers.py +++ b/google/cloud/talent_v4beta1/services/profile_service/pagers.py @@ -15,7 +15,16 @@ # 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 +35,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 +44,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 +62,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 +97,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 +106,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. """ @@ -115,9 +124,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. @@ -154,7 +163,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 +172,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 +190,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 +225,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 +234,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. """ @@ -243,9 +252,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. 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..3a1c0f76 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/profile_service/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -119,6 +119,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -135,6 +136,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -151,6 +153,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..a3dbfe39 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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, ) -> None: @@ -91,6 +92,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): @@ -105,72 +110,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, + ) - # 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,17 +171,8 @@ 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( @@ -202,7 +186,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 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..9c405dac 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 @@ -65,7 +65,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 @@ -105,6 +105,7 @@ def __init__( 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, ) -> None: @@ -136,12 +137,16 @@ 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. Raises: @@ -150,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" - ) + 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, + ) - # 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 +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/tenant_service/async_client.py b/google/cloud/talent_v4beta1/services/tenant_service/async_client.py index be6fce85..047dffe9 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/async_client.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/async_client.py @@ -80,7 +80,36 @@ class TenantServiceAsyncClient: 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 @@ -157,7 +186,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,10 +195,11 @@ 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 @@ -182,7 +212,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 @@ -244,7 +274,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,6 +284,7 @@ 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. @@ -265,7 +296,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 @@ -304,6 +335,7 @@ async def get_tenant( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -333,13 +365,14 @@ 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. @@ -351,7 +384,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 @@ -413,7 +446,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,6 +454,7 @@ 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. @@ -460,6 +494,7 @@ async def delete_tenant( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, @@ -488,7 +523,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,6 +532,7 @@ 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. @@ -508,7 +544,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 @@ -544,6 +580,7 @@ async def list_tenants( predicate=retries.if_exception_type( exceptions.DeadlineExceeded, 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..e0750d74 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/client.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/client.py @@ -112,6 +112,22 @@ 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 @@ -124,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 @@ -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,17 @@ 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() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -325,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, ) @@ -343,19 +355,20 @@ 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 @@ -368,7 +381,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 @@ -431,16 +444,17 @@ 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. @@ -452,7 +466,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 @@ -513,13 +527,14 @@ 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. @@ -531,7 +546,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 @@ -594,14 +609,15 @@ 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. @@ -662,15 +678,16 @@ 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. @@ -682,7 +699,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 diff --git a/google/cloud/talent_v4beta1/services/tenant_service/pagers.py b/google/cloud/talent_v4beta1/services/tenant_service/pagers.py index 99dfee65..5d402971 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/pagers.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/pagers.py @@ -15,7 +15,16 @@ # 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 +34,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 +43,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 +61,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 +96,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 +105,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. """ @@ -114,9 +123,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. 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..73ae1b06 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -122,6 +122,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -138,6 +139,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, @@ -151,6 +153,7 @@ def _prep_wrapped_messages(self, client_info): predicate=retries.if_exception_type( exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=30.0, ), default_timeout=30.0, client_info=client_info, 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..f187b6c1 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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, ) -> None: @@ -91,6 +92,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): @@ -105,72 +110,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, + ) - # 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,17 +171,8 @@ 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( @@ -202,7 +186,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 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..59aa7ff4 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 @@ -65,7 +65,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 @@ -105,6 +105,7 @@ def __init__( 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, ) -> None: @@ -136,12 +137,16 @@ 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. Raises: @@ -150,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" - ) + 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, + ) - # 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 +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/types/__init__.py b/google/cloud/talent_v4beta1/types/__init__.py index 3d326265..98bf50a7 100644 --- a/google/cloud/talent_v4beta1/types/__init__.py +++ b/google/cloud/talent_v4beta1/types/__init__.py @@ -15,52 +15,52 @@ # 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 +73,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 +97,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..41eda976 100644 --- a/google/cloud/talent_v4beta1/types/application.py +++ b/google/cloud/talent_v4beta1/types/application.py @@ -69,9 +69,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 +79,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 +99,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 diff --git a/google/cloud/talent_v4beta1/types/application_service.py b/google/cloud/talent_v4beta1/types/application_service.py index 8c906e91..81a0bae8 100644 --- a/google/cloud/talent_v4beta1/types/application_service.py +++ b/google/cloud/talent_v4beta1/types/application_service.py @@ -47,7 +47,7 @@ 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. """ @@ -79,10 +79,10 @@ 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 @@ -152,11 +152,11 @@ 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. """ diff --git a/google/cloud/talent_v4beta1/types/common.py b/google/cloud/talent_v4beta1/types/common.py index 61614a0a..3d6d81ba 100644 --- a/google/cloud/talent_v4beta1/types/common.py +++ b/google/cloud/talent_v4beta1/types/common.py @@ -187,6 +187,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 @@ -254,9 +255,9 @@ 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). """ @@ -270,7 +271,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 +279,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): @@ -390,7 +391,7 @@ 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. """ @@ -426,7 +427,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 @@ -532,14 +533,14 @@ 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 +550,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 +632,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] @@ -693,12 +694,12 @@ 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 @@ -727,10 +728,10 @@ class Certification(proto.Message): 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. @@ -760,9 +761,9 @@ class Skill(proto.Message): 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): @@ -791,9 +792,9 @@ 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). """ @@ -835,7 +836,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 +848,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``. diff --git a/google/cloud/talent_v4beta1/types/company.py b/google/cloud/talent_v4beta1/types/company.py index ac333e29..ed091608 100644 --- a/google/cloud/talent_v4beta1/types/company.py +++ b/google/cloud/talent_v4beta1/types/company.py @@ -53,7 +53,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 +92,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): @@ -106,7 +106,7 @@ 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] diff --git a/google/cloud/talent_v4beta1/types/company_service.py b/google/cloud/talent_v4beta1/types/company_service.py index 960ab39c..ab1de2b8 100644 --- a/google/cloud/talent_v4beta1/types/company_service.py +++ b/google/cloud/talent_v4beta1/types/company_service.py @@ -48,7 +48,7 @@ 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. """ @@ -80,10 +80,10 @@ 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 @@ -165,11 +165,11 @@ 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. """ diff --git a/google/cloud/talent_v4beta1/types/completion_service.py b/google/cloud/talent_v4beta1/types/completion_service.py index 69f4882a..1b53f07e 100644 --- a/google/cloud/talent_v4beta1/types/completion_service.py +++ b/google/cloud/talent_v4beta1/types/completion_service.py @@ -63,10 +63,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]. """ @@ -103,10 +103,10 @@ 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. """ @@ -117,7 +117,7 @@ class CompletionResult(proto.Message): 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 diff --git a/google/cloud/talent_v4beta1/types/event.py b/google/cloud/talent_v4beta1/types/event.py index 4583b654..70cec508 100644 --- a/google/cloud/talent_v4beta1/types/event.py +++ b/google/cloud/talent_v4beta1/types/event.py @@ -45,13 +45,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. @@ -81,7 +81,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]): @@ -139,7 +139,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 diff --git a/google/cloud/talent_v4beta1/types/event_service.py b/google/cloud/talent_v4beta1/types/event_service.py index dad4a639..d389c18f 100644 --- a/google/cloud/talent_v4beta1/types/event_service.py +++ b/google/cloud/talent_v4beta1/types/event_service.py @@ -38,7 +38,7 @@ 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. diff --git a/google/cloud/talent_v4beta1/types/filters.py b/google/cloud/talent_v4beta1/types/filters.py index 48d631b4..70f87f90 100644 --- a/google/cloud/talent_v4beta1/types/filters.py +++ b/google/cloud/talent_v4beta1/types/filters.py @@ -90,7 +90,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 +108,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 +119,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 +143,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 +182,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 +205,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]): @@ -259,7 +259,7 @@ class ProfileQuery(proto.Message): 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 +379,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 +396,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 +412,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 +428,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 +444,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 +458,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 +507,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 +528,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 +548,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, @@ -635,7 +635,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 +644,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. @@ -701,12 +701,12 @@ 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 @@ -738,13 +738,13 @@ 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 +754,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 @@ -831,7 +831,7 @@ class EmployerFilter(proto.Message): 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. @@ -872,7 +872,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 @@ -901,10 +901,10 @@ 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). """ @@ -927,11 +927,11 @@ 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. @@ -996,17 +996,17 @@ 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 @@ -1043,9 +1043,9 @@ 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): diff --git a/google/cloud/talent_v4beta1/types/histogram.py b/google/cloud/talent_v4beta1/types/histogram.py index 6c72e53e..b809ac0b 100644 --- a/google/cloud/talent_v4beta1/types/histogram.py +++ b/google/cloud/talent_v4beta1/types/histogram.py @@ -50,7 +50,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. diff --git a/google/cloud/talent_v4beta1/types/job.py b/google/cloud/talent_v4beta1/types/job.py index 147fbe55..a378bbd5 100644 --- a/google/cloud/talent_v4beta1/types/job.py +++ b/google/cloud/talent_v4beta1/types/job.py @@ -117,15 +117,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 +140,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 +148,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 +173,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 +208,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 +224,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 +232,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,19 +304,19 @@ 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. """ @@ -356,7 +356,7 @@ 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 +364,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]. @@ -385,7 +385,7 @@ class ProcessingOptions(proto.Message): 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: diff --git a/google/cloud/talent_v4beta1/types/job_service.py b/google/cloud/talent_v4beta1/types/job_service.py index 5cad2836..8ee4d6fa 100644 --- a/google/cloud/talent_v4beta1/types/job_service.py +++ b/google/cloud/talent_v4beta1/types/job_service.py @@ -73,7 +73,7 @@ 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. """ @@ -104,9 +104,9 @@ 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 @@ -221,7 +221,7 @@ 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] @@ -243,13 +243,13 @@ 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. """ @@ -276,17 +276,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 +307,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 +420,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 +512,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 +524,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 +582,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. @@ -679,17 +679,17 @@ 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 +708,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 +723,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 +732,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,7 +752,7 @@ 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]. """ @@ -773,10 +773,10 @@ 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 @@ -831,7 +831,7 @@ 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. """ @@ -852,9 +852,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. @@ -897,7 +897,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. @@ -907,7 +907,7 @@ 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 +917,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] diff --git a/google/cloud/talent_v4beta1/types/profile.py b/google/cloud/talent_v4beta1/types/profile.py index 38428498..33c9a31f 100644 --- a/google/cloud/talent_v4beta1/types/profile.py +++ b/google/cloud/talent_v4beta1/types/profile.py @@ -95,16 +95,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 +130,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 +139,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 +183,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 +197,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 +215,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 +232,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 +258,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 +290,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]. @@ -390,12 +390,12 @@ 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 @@ -439,7 +439,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]. """ @@ -463,7 +463,7 @@ class PersonName(proto.Message): 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): @@ -538,7 +538,7 @@ 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,10 +547,10 @@ 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. """ @@ -570,7 +570,7 @@ 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): @@ -587,10 +587,10 @@ 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): @@ -647,7 +647,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): @@ -671,9 +671,9 @@ 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 +685,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 +695,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 @@ -752,11 +752,11 @@ 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 +764,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 +772,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 @@ -824,7 +824,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. @@ -859,9 +859,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 +870,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. @@ -939,7 +939,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. @@ -981,10 +981,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,7 +995,7 @@ 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. """ diff --git a/google/cloud/talent_v4beta1/types/profile_service.py b/google/cloud/talent_v4beta1/types/profile_service.py index 1214e0ab..c64b7c3d 100644 --- a/google/cloud/talent_v4beta1/types/profile_service.py +++ b/google/cloud/talent_v4beta1/types/profile_service.py @@ -81,7 +81,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. @@ -105,7 +105,7 @@ 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. @@ -132,7 +132,7 @@ class CreateProfileRequest(proto.Message): 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. """ @@ -160,9 +160,9 @@ 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. @@ -197,13 +197,13 @@ class SearchProfilesRequest(proto.Message): 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 +273,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]. @@ -463,18 +463,18 @@ class SearchProfilesResponse(proto.Message): 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): @@ -513,10 +513,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. diff --git a/google/cloud/talent_v4beta1/types/tenant.py b/google/cloud/talent_v4beta1/types/tenant.py index c7d1974d..c399eba2 100644 --- a/google/cloud/talent_v4beta1/types/tenant.py +++ b/google/cloud/talent_v4beta1/types/tenant.py @@ -43,7 +43,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. diff --git a/google/cloud/talent_v4beta1/types/tenant_service.py b/google/cloud/talent_v4beta1/types/tenant_service.py index 505da6f7..104c43c7 100644 --- a/google/cloud/talent_v4beta1/types/tenant_service.py +++ b/google/cloud/talent_v4beta1/types/tenant_service.py @@ -46,7 +46,7 @@ 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. """ @@ -73,10 +73,10 @@ 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 @@ -139,11 +139,11 @@ 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. """ diff --git a/noxfile.py b/noxfile.py index 41eeb037..d2747a77 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): @@ -70,17 +87,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,6 +122,9 @@ 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") @@ -110,6 +134,9 @@ def system(session): # 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 +149,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 +179,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") diff --git a/renovate.json b/renovate.json index 4fa94931..f08bc22c 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,6 @@ { "extends": [ "config:base", ":preserveSemverRanges" - ] + ], + "ignorePaths": [".pre-commit-config.yaml"] } diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index bca0522e..97bf7da8 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -85,7 +85,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'] diff --git a/setup.py b/setup.py index 6cd77735..1dc00641 100644 --- a/setup.py +++ b/setup.py @@ -29,11 +29,10 @@ # '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.22.2, < 2.0.0dev", + "proto-plus >= 1.15.0", ] -extras = {} +extras = {"libcst": "libcst >= 0.2.5"} # Setup boilerplate below this line. diff --git a/synth.metadata b/synth.metadata index 83804676..7fbfc295 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-talent.git", - "sha": "8a53830a77532e25ff0794e9fb5400e4ec01d4f5" + "remote": "git@github.com:googleapis/python-talent", + "sha": "8a12124259ca87c5064fabe9f058ed966eea2d56" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "8a6f4d9acb1620af2156b42b37b54eae257b7cad", - "internalRef": "348696929" + "sha": "ef705a6d9fd6dcd8f0b13e012cb284332734785b", + "internalRef": "365856330" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" + "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "41a4e56982620d3edcf110d76f4fcdfdec471ac8" + "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" } } ], @@ -49,255 +49,5 @@ "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/synth.py b/synth.py index bc3d5083..a8573b62 100644 --- a/synth.py +++ b/synth.py @@ -48,7 +48,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/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 2923be13..cc205f2a 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -5,6 +5,5 @@ # # 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.22.2 +proto-plus==1.15.0 diff --git a/tests/unit/gapic/talent_v4/__init__.py b/tests/unit/gapic/talent_v4/__init__.py index 8b137891..42ffdf2b 100644 --- a/tests/unit/gapic/talent_v4/__init__.py +++ b/tests/unit/gapic/talent_v4/__init__.py @@ -1 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/talent_v4/test_company_service.py b/tests/unit/gapic/talent_v4/test_company_service.py index bcb62811..eaa1a863 100644 --- a/tests/unit/gapic/talent_v4/test_company_service.py +++ b/tests/unit/gapic/talent_v4/test_company_service.py @@ -91,7 +91,24 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -101,16 +118,21 @@ def test_company_service_client_from_service_account_file(client_class): 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 @@ -161,7 +183,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 +199,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 +215,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 +243,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 +294,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 +321,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 +393,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 +423,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 +442,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, ) @@ -517,6 +522,22 @@ 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=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 @@ -794,6 +815,22 @@ 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=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 @@ -1059,6 +1096,22 @@ 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=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 @@ -1300,6 +1353,22 @@ 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=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 @@ -1485,6 +1554,22 @@ 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=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 @@ -1937,6 +2022,54 @@ def test_company_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompanyServiceGrpcTransport, + transports.CompanyServiceGrpcAsyncIOTransport, + ], +) +def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -1956,7 +2089,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 +2101,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 +2112,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 +2128,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 @@ -2034,6 +2169,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 +2186,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 diff --git a/tests/unit/gapic/talent_v4/test_completion.py b/tests/unit/gapic/talent_v4/test_completion.py index cafd4bc5..e4ed8c02 100644 --- a/tests/unit/gapic/talent_v4/test_completion.py +++ b/tests/unit/gapic/talent_v4/test_completion.py @@ -81,7 +81,22 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( @@ -90,16 +105,21 @@ def test_completion_client_from_service_account_file(client_class): 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 @@ -148,7 +168,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 +184,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 +200,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 +228,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 +277,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 +304,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 +376,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 +406,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 +423,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, ) @@ -459,6 +462,22 @@ 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=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", @@ -603,7 +622,7 @@ 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. @@ -710,6 +729,51 @@ def test_completion_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport], +) +def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -729,7 +793,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 +805,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 +816,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 +827,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 @@ -802,6 +868,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 +882,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 diff --git a/tests/unit/gapic/talent_v4/test_event_service.py b/tests/unit/gapic/talent_v4/test_event_service.py index dcf80843..e28dd92b 100644 --- a/tests/unit/gapic/talent_v4/test_event_service.py +++ b/tests/unit/gapic/talent_v4/test_event_service.py @@ -82,7 +82,22 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( @@ -91,16 +106,21 @@ def test_event_service_client_from_service_account_file(client_class): 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 @@ -149,7 +169,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 +185,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 +201,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 +229,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 +278,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 +305,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 +377,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 +407,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 +424,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, ) @@ -473,6 +476,24 @@ 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=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 @@ -713,7 +734,10 @@ 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. @@ -820,6 +844,51 @@ def test_event_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport], +) +def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -839,7 +908,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 +920,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 +931,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 +942,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 @@ -912,6 +983,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 +997,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 diff --git a/tests/unit/gapic/talent_v4/test_job_service.py b/tests/unit/gapic/talent_v4/test_job_service.py index 208347d4..d0254e33 100644 --- a/tests/unit/gapic/talent_v4/test_job_service.py +++ b/tests/unit/gapic/talent_v4/test_job_service.py @@ -98,7 +98,22 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( @@ -107,16 +122,21 @@ def test_job_service_client_from_service_account_file(client_class): 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 @@ -165,7 +185,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 +201,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 +217,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 +245,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 +294,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 +321,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 +393,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 +423,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 +440,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, ) @@ -532,6 +535,22 @@ 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=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 @@ -786,6 +805,24 @@ 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=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 @@ -1051,6 +1088,22 @@ 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=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 @@ -1348,6 +1401,22 @@ 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=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 @@ -1604,6 +1673,24 @@ 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=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 @@ -1810,6 +1897,22 @@ 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=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 @@ -1992,6 +2095,24 @@ 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=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 @@ -2203,6 +2324,22 @@ 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=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 @@ -2512,6 +2649,22 @@ 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=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 @@ -2656,6 +2809,24 @@ 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=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 @@ -2815,7 +2986,7 @@ 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. @@ -2938,6 +3109,51 @@ def test_job_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport], +) +def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -2957,7 +3173,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 +3185,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 +3196,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 +3207,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 @@ -3030,6 +3248,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 +3262,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 diff --git a/tests/unit/gapic/talent_v4/test_tenant_service.py b/tests/unit/gapic/talent_v4/test_tenant_service.py index 32438832..64e5cbbb 100644 --- a/tests/unit/gapic/talent_v4/test_tenant_service.py +++ b/tests/unit/gapic/talent_v4/test_tenant_service.py @@ -88,7 +88,24 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -98,16 +115,21 @@ def test_tenant_service_client_from_service_account_file(client_class): 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 @@ -158,7 +180,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 +196,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 +212,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 +240,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 +291,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 +318,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 +390,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 +420,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 +439,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, ) @@ -479,6 +484,22 @@ 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=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 @@ -684,6 +705,22 @@ 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=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 @@ -877,6 +914,22 @@ 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=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 @@ -1077,6 +1130,22 @@ 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=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 @@ -1262,6 +1331,22 @@ 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=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 @@ -1712,6 +1797,54 @@ def test_tenant_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.TenantServiceGrpcTransport, + transports.TenantServiceGrpcAsyncIOTransport, + ], +) +def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -1731,7 +1864,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 +1876,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 +1887,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 +1901,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 @@ -1807,6 +1942,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 +1959,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 diff --git a/tests/unit/gapic/talent_v4beta1/__init__.py b/tests/unit/gapic/talent_v4beta1/__init__.py index 8b137891..42ffdf2b 100644 --- a/tests/unit/gapic/talent_v4beta1/__init__.py +++ b/tests/unit/gapic/talent_v4beta1/__init__.py @@ -1 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/talent_v4beta1/test_application_service.py b/tests/unit/gapic/talent_v4beta1/test_application_service.py index 9504a896..68c75313 100644 --- a/tests/unit/gapic/talent_v4beta1/test_application_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_application_service.py @@ -97,7 +97,24 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -107,16 +124,21 @@ def test_application_service_client_from_service_account_file(client_class): 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 @@ -167,7 +189,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 +205,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 +221,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 +249,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 +310,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 +337,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 +409,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 +439,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 +458,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, ) @@ -525,6 +530,24 @@ 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=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", @@ -805,6 +828,22 @@ 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=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", @@ -1063,6 +1102,24 @@ 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=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", @@ -1309,6 +1366,24 @@ 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=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", @@ -1513,6 +1588,24 @@ 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=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", @@ -2018,6 +2111,56 @@ def test_application_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ApplicationServiceGrpcTransport, + transports.ApplicationServiceGrpcAsyncIOTransport, + ], +) +def test_application_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -2037,7 +2180,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 +2192,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 +2203,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 +2219,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 @@ -2115,6 +2260,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 +2277,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 diff --git a/tests/unit/gapic/talent_v4beta1/test_company_service.py b/tests/unit/gapic/talent_v4beta1/test_company_service.py index 603a1904..973e425a 100644 --- a/tests/unit/gapic/talent_v4beta1/test_company_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_company_service.py @@ -93,7 +93,24 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -103,16 +120,21 @@ def test_company_service_client_from_service_account_file(client_class): 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 @@ -163,7 +185,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 +201,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 +217,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 +245,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 +296,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 +323,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 +395,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 +425,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 +444,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, ) @@ -519,6 +524,22 @@ 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=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 @@ -796,6 +817,22 @@ 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=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 @@ -1061,6 +1098,22 @@ 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=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 @@ -1292,6 +1345,22 @@ 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=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 @@ -1477,6 +1546,22 @@ 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=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 @@ -1929,6 +2014,54 @@ def test_company_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CompanyServiceGrpcTransport, + transports.CompanyServiceGrpcAsyncIOTransport, + ], +) +def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -1948,7 +2081,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 +2093,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 +2104,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 +2120,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 @@ -2026,6 +2161,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 +2178,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 diff --git a/tests/unit/gapic/talent_v4beta1/test_completion.py b/tests/unit/gapic/talent_v4beta1/test_completion.py index b03a7da9..48f3e828 100644 --- a/tests/unit/gapic/talent_v4beta1/test_completion.py +++ b/tests/unit/gapic/talent_v4beta1/test_completion.py @@ -81,7 +81,22 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( @@ -90,16 +105,21 @@ def test_completion_client_from_service_account_file(client_class): 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 @@ -148,7 +168,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 +184,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 +200,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 +228,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 +277,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 +304,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 +376,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 +406,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 +423,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, ) @@ -459,6 +462,22 @@ 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=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", @@ -603,7 +622,7 @@ 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. @@ -710,6 +729,51 @@ def test_completion_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [transports.CompletionGrpcTransport, transports.CompletionGrpcAsyncIOTransport], +) +def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -729,7 +793,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 +805,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 +816,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 +827,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 @@ -802,6 +868,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 +882,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 diff --git a/tests/unit/gapic/talent_v4beta1/test_event_service.py b/tests/unit/gapic/talent_v4beta1/test_event_service.py index a5f2b7c0..16e25afe 100644 --- a/tests/unit/gapic/talent_v4beta1/test_event_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_event_service.py @@ -82,7 +82,22 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( @@ -91,16 +106,21 @@ def test_event_service_client_from_service_account_file(client_class): 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 @@ -149,7 +169,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 +185,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 +201,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 +229,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 +278,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 +305,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 +377,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 +407,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 +424,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, ) @@ -473,6 +476,24 @@ 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=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 @@ -713,7 +734,10 @@ 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. @@ -820,6 +844,51 @@ def test_event_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [transports.EventServiceGrpcTransport, transports.EventServiceGrpcAsyncIOTransport], +) +def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -839,7 +908,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 +920,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 +931,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 +942,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 @@ -912,6 +983,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 +997,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 diff --git a/tests/unit/gapic/talent_v4beta1/test_job_service.py b/tests/unit/gapic/talent_v4beta1/test_job_service.py index 43896c99..db29e42b 100644 --- a/tests/unit/gapic/talent_v4beta1/test_job_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_job_service.py @@ -98,7 +98,22 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() with mock.patch.object( @@ -107,16 +122,21 @@ def test_job_service_client_from_service_account_file(client_class): 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 @@ -165,7 +185,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 +201,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 +217,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 +245,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 +294,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 +321,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 +393,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 +423,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 +440,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, ) @@ -532,6 +535,22 @@ 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=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 @@ -786,6 +805,24 @@ 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=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 @@ -1051,6 +1088,22 @@ 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=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 @@ -1348,6 +1401,22 @@ 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=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 @@ -1590,6 +1659,24 @@ 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=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 @@ -1796,6 +1883,22 @@ 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=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 @@ -1978,6 +2081,24 @@ 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=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 @@ -2183,6 +2304,22 @@ 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=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 @@ -2493,6 +2630,22 @@ 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=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 @@ -2799,6 +2952,24 @@ 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=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 @@ -3127,7 +3298,7 @@ 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. @@ -3250,6 +3421,51 @@ def test_job_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [transports.JobServiceGrpcTransport, transports.JobServiceGrpcAsyncIOTransport], +) +def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -3269,7 +3485,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 +3497,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 +3508,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 +3519,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 @@ -3342,6 +3560,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 +3574,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 diff --git a/tests/unit/gapic/talent_v4beta1/test_profile_service.py b/tests/unit/gapic/talent_v4beta1/test_profile_service.py index 136e0be1..843a00c4 100644 --- a/tests/unit/gapic/talent_v4beta1/test_profile_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_profile_service.py @@ -99,7 +99,24 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -109,16 +126,21 @@ def test_profile_service_client_from_service_account_file(client_class): 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 @@ -169,7 +191,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 +207,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 +223,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 +251,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 +302,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 +329,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 +401,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 +431,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 +450,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, ) @@ -488,6 +493,22 @@ 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=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 @@ -829,6 +850,22 @@ 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=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 @@ -1080,6 +1117,22 @@ 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=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 @@ -1319,6 +1372,22 @@ 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=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 @@ -1537,6 +1606,22 @@ 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=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 @@ -1728,6 +1813,22 @@ 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=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 @@ -2160,6 +2261,54 @@ def test_profile_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProfileServiceGrpcTransport, + transports.ProfileServiceGrpcAsyncIOTransport, + ], +) +def test_profile_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -2179,7 +2328,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 +2340,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 +2351,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 +2367,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 @@ -2257,6 +2408,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 +2425,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 diff --git a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py index 62a13dd4..e4e6acc6 100644 --- a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py @@ -88,7 +88,24 @@ 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 = 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_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -98,16 +115,21 @@ def test_tenant_service_client_from_service_account_file(client_class): 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 @@ -158,7 +180,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 +196,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 +212,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 +240,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 +291,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 +318,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 +390,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 +420,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 +439,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, ) @@ -490,6 +495,22 @@ 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=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 @@ -719,6 +740,22 @@ 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=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 @@ -936,6 +973,22 @@ 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=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 @@ -1139,6 +1192,22 @@ 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=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 @@ -1324,6 +1393,22 @@ 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=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 @@ -1774,6 +1859,54 @@ def test_tenant_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.TenantServiceGrpcTransport, + transports.TenantServiceGrpcAsyncIOTransport, + ], +) +def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = 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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + 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(), @@ -1793,7 +1926,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 +1938,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 +1949,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 +1963,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 @@ -1869,6 +2004,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 +2021,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 From 12d77fa03a5b4757e74c40f5aa7d4e60bcebf4c2 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Wed, 31 Mar 2021 12:28:20 -0700 Subject: [PATCH 04/26] build(python): update docfx job to use new plugin (#77) * changes without context * build(python): update docfx job to use new plugin Source-Author: Dan Lee <71398022+dandhlee@users.noreply.github.com> Source-Date: Tue Mar 30 19:36:37 2021 -0400 Source-Repo: googleapis/synthtool Source-Sha: 4501974ad08b5d693311457e2ea4ce845676e329 Source-Link: https://github.com/googleapis/synthtool/commit/4501974ad08b5d693311457e2ea4ce845676e329 --- google/cloud/talent_v4/__init__.py | 4 +- google/cloud/talent_v4beta1/__init__.py | 4 +- noxfile.py | 4 +- synth.metadata | 277 +++++++++++++++++++++++- 4 files changed, 278 insertions(+), 11 deletions(-) diff --git a/google/cloud/talent_v4/__init__.py b/google/cloud/talent_v4/__init__.py index b193e4de..1d4b845e 100644 --- a/google/cloud/talent_v4/__init__.py +++ b/google/cloud/talent_v4/__init__.py @@ -127,7 +127,6 @@ "JobLevel", "JobQuery", "JobResult", - "JobServiceClient", "JobView", "ListCompaniesRequest", "ListCompaniesResponse", @@ -144,10 +143,11 @@ "SearchJobsResponse", "SpellingCorrection", "Tenant", + "TenantServiceClient", "TimestampRange", "UpdateCompanyRequest", "UpdateJobRequest", "UpdateTenantRequest", "Visibility", - "TenantServiceClient", + "JobServiceClient", ) diff --git a/google/cloud/talent_v4beta1/__init__.py b/google/cloud/talent_v4beta1/__init__.py index 4743ac58..ea0ffd24 100644 --- a/google/cloud/talent_v4beta1/__init__.py +++ b/google/cloud/talent_v4beta1/__init__.py @@ -163,7 +163,6 @@ "CompensationInfo", "CompleteQueryRequest", "CompleteQueryResponse", - "CompletionClient", "ContactInfoUsage", "CreateApplicationRequest", "CreateClientEventRequest", @@ -244,6 +243,7 @@ "SpellingCorrection", "SummarizedProfile", "Tenant", + "TenantServiceClient", "TimeFilter", "TimestampRange", "UpdateApplicationRequest", @@ -253,5 +253,5 @@ "UpdateTenantRequest", "Visibility", "WorkExperienceFilter", - "TenantServiceClient", + "CompletionClient", ) diff --git a/noxfile.py b/noxfile.py index d2747a77..6e8aafb9 100644 --- a/noxfile.py +++ b/noxfile.py @@ -211,9 +211,7 @@ 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", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/synth.metadata b/synth.metadata index 7fbfc295..5af71e53 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,8 +3,8 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-talent", - "sha": "8a12124259ca87c5064fabe9f058ed966eea2d56" + "remote": "https://github.com/googleapis/python-talent.git", + "sha": "095747e8b517769a9caa2df6babf96fd526d0a22" } }, { @@ -19,14 +19,14 @@ "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" + "sha": "4501974ad08b5d693311457e2ea4ce845676e329" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "572ef8f70edd9041f5bcfa71511aed6aecfc2098" + "sha": "4501974ad08b5d693311457e2ea4ce845676e329" } } ], @@ -49,5 +49,274 @@ "generator": "bazel" } } + ], + "generatedFiles": [ + ".coveragerc", + ".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/header-checker-lint.yml", + ".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-head.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-head.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-head.cfg", + ".kokoro/samples/python3.8/periodic.cfg", + ".kokoro/samples/python3.8/presubmit.cfg", + ".kokoro/test-samples-against-head.sh", + ".kokoro/test-samples-impl.sh", + ".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/company_service.rst", + "docs/talent_v4/completion.rst", + "docs/talent_v4/event_service.rst", + "docs/talent_v4/job_service.rst", + "docs/talent_v4/services.rst", + "docs/talent_v4/tenant_service.rst", + "docs/talent_v4/types.rst", + "docs/talent_v4beta1/application_service.rst", + "docs/talent_v4beta1/company_service.rst", + "docs/talent_v4beta1/completion.rst", + "docs/talent_v4beta1/event_service.rst", + "docs/talent_v4beta1/job_service.rst", + "docs/talent_v4beta1/profile_service.rst", + "docs/talent_v4beta1/services.rst", + "docs/talent_v4beta1/tenant_service.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 From 7c1617a5302881411c4c500951c7dc7bfb642515 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Fri, 2 Apr 2021 08:02:19 -0700 Subject: [PATCH 05/26] chore: sort class names (#78) --- google/cloud/talent_v4/__init__.py | 4 ++-- google/cloud/talent_v4beta1/__init__.py | 4 ++-- synth.metadata | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/google/cloud/talent_v4/__init__.py b/google/cloud/talent_v4/__init__.py index 1d4b845e..b193e4de 100644 --- a/google/cloud/talent_v4/__init__.py +++ b/google/cloud/talent_v4/__init__.py @@ -127,6 +127,7 @@ "JobLevel", "JobQuery", "JobResult", + "JobServiceClient", "JobView", "ListCompaniesRequest", "ListCompaniesResponse", @@ -143,11 +144,10 @@ "SearchJobsResponse", "SpellingCorrection", "Tenant", - "TenantServiceClient", "TimestampRange", "UpdateCompanyRequest", "UpdateJobRequest", "UpdateTenantRequest", "Visibility", - "JobServiceClient", + "TenantServiceClient", ) diff --git a/google/cloud/talent_v4beta1/__init__.py b/google/cloud/talent_v4beta1/__init__.py index ea0ffd24..4bfd0d8b 100644 --- a/google/cloud/talent_v4beta1/__init__.py +++ b/google/cloud/talent_v4beta1/__init__.py @@ -163,6 +163,7 @@ "CompensationInfo", "CompleteQueryRequest", "CompleteQueryResponse", + "CompletionClient", "ContactInfoUsage", "CreateApplicationRequest", "CreateClientEventRequest", @@ -227,7 +228,6 @@ "Profile", "ProfileEvent", "ProfileQuery", - "ProfileServiceClient", "Publication", "Rating", "RequestMetadata", @@ -253,5 +253,5 @@ "UpdateTenantRequest", "Visibility", "WorkExperienceFilter", - "CompletionClient", + "ProfileServiceClient", ) diff --git a/synth.metadata b/synth.metadata index 5af71e53..cd4594bf 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-talent.git", - "sha": "095747e8b517769a9caa2df6babf96fd526d0a22" + "sha": "12d77fa03a5b4757e74c40f5aa7d4e60bcebf4c2" } }, { From 49018f01c059fdacbb290b3bdc085bb61677c490 Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Fri, 16 Apr 2021 17:31:29 -0400 Subject: [PATCH 06/26] chore: prevent normalization of semver versioning (#84) * chore: prevent normalization of semver versioning * chore: update workaround to make sic work --- setup.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 1dc00641..806cecd9 100644 --- a/setup.py +++ b/setup.py @@ -17,6 +17,20 @@ import setuptools +# Disable version normalization performed by setuptools.setup() +try: + # Try the approach of using sic(), added in setuptools 46.1.0 + from setuptools import sic +except ImportError: + # Try the approach of replacing packaging.version.Version + sic = lambda v: v + try: + # setuptools >=39.0.0 uses packaging from setuptools.extern + from setuptools.extern import packaging + except ImportError: + # setuptools <39.0.0 uses packaging from pkg_resources.extern + from pkg_resources.extern import packaging + packaging.version.Version = packaging.version.LegacyVersion # Package metadata. @@ -59,7 +73,7 @@ setuptools.setup( name=name, - version=version, + version=sic(version), description=description, long_description=readme, author="Google LLC", From 9dd06e070310567c62749954cd7c2a52f4d7963b Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Tue, 27 Apr 2021 14:53:27 -0400 Subject: [PATCH 07/26] chore(revert): revert preventing normalization (#85) --- setup.py | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/setup.py b/setup.py index 806cecd9..1dc00641 100644 --- a/setup.py +++ b/setup.py @@ -17,20 +17,6 @@ import setuptools -# Disable version normalization performed by setuptools.setup() -try: - # Try the approach of using sic(), added in setuptools 46.1.0 - from setuptools import sic -except ImportError: - # Try the approach of replacing packaging.version.Version - sic = lambda v: v - try: - # setuptools >=39.0.0 uses packaging from setuptools.extern - from setuptools.extern import packaging - except ImportError: - # setuptools <39.0.0 uses packaging from pkg_resources.extern - from pkg_resources.extern import packaging - packaging.version.Version = packaging.version.LegacyVersion # Package metadata. @@ -73,7 +59,7 @@ setuptools.setup( name=name, - version=sic(version), + version=version, description=description, long_description=readme, author="Google LLC", From b62b649864fc7320fecf6b92390e24c71eb85aa9 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Sun, 9 May 2021 21:08:02 -0400 Subject: [PATCH 08/26] chore: migrate to owl bot (#87) This PR migrates from autosynth to [owl bot](https://github.com/googleapis/repo-automation-bots/tree/master/packages/owl-bot). owl bot will save time for maintainers as it will automatically open PRs when there are updates in [googleapis-gen](https://github.com/googleapis/googleapis-gen/tree/master/google) without requiring maintainers to run `synthtool` to build the client from protos. Additionally, similar to autosynth, PRs will be automatically opened when there are template updates. With owl bot, on every PR, a post-processor image will run so that we won't have to ask contributors to run [blacken](https://github.com/googleapis/python-talent/blob/master/synth.py#L65). --- .github/.OwlBot.lock.yaml | 4 + .github/.OwlBot.yaml | 26 ++ .github/header-checker-lint.yml | 2 +- .kokoro/release.sh | 4 +- .kokoro/release/common.cfg | 14 +- .pre-commit-config.yaml | 14 ++ docs/_static/custom.css | 13 +- docs/conf.py | 13 + google/cloud/talent_v4beta1/__init__.py | 4 +- synth.py => owlbot.py | 29 +-- renovate.json | 5 +- samples/snippets/noxfile.py | 10 +- synth.metadata | 322 ------------------------ 13 files changed, 97 insertions(+), 363 deletions(-) create mode 100644 .github/.OwlBot.lock.yaml create mode 100644 .github/.OwlBot.yaml rename synth.py => owlbot.py (70%) delete mode 100644 synth.metadata diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 00000000..29084e8a --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,4 @@ +docker: + digest: sha256:cfc0e802701262c211703c468874d767f65dabe6a1a71d0e07bfc8a3d5175f32 + image: gcr.io/repo-automation-bots/owlbot-python:latest + 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 index fc281c05..6fe78aa7 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], "sourceFileExtensions": [ "ts", "js", 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/.pre-commit-config.yaml b/.pre-commit-config.yaml index 32302e48..8912e9b5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,17 @@ +# 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: diff --git a/docs/_static/custom.css b/docs/_static/custom.css index bcd37bbd..b0a29546 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -1,9 +1,20 @@ div#python2-eol { border-color: red; border-width: medium; -} +} /* 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..77a0276d 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 # diff --git a/google/cloud/talent_v4beta1/__init__.py b/google/cloud/talent_v4beta1/__init__.py index 4bfd0d8b..4743ac58 100644 --- a/google/cloud/talent_v4beta1/__init__.py +++ b/google/cloud/talent_v4beta1/__init__.py @@ -228,6 +228,7 @@ "Profile", "ProfileEvent", "ProfileQuery", + "ProfileServiceClient", "Publication", "Rating", "RequestMetadata", @@ -243,7 +244,6 @@ "SpellingCorrection", "SummarizedProfile", "Tenant", - "TenantServiceClient", "TimeFilter", "TimestampRange", "UpdateApplicationRequest", @@ -253,5 +253,5 @@ "UpdateTenantRequest", "Visibility", "WorkExperienceFilter", - "ProfileServiceClient", + "TenantServiceClient", ) diff --git a/synth.py b/owlbot.py similarity index 70% rename from synth.py rename to owlbot.py index a8573b62..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 diff --git a/renovate.json b/renovate.json index f08bc22c..c0489556 100644 --- a/renovate.json +++ b/renovate.json @@ -2,5 +2,8 @@ "extends": [ "config:base", ":preserveSemverRanges" ], - "ignorePaths": [".pre-commit-config.yaml"] + "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 97bf7da8..956cdf4f 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -172,10 +172,16 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: """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/synth.metadata b/synth.metadata deleted file mode 100644 index cd4594bf..00000000 --- a/synth.metadata +++ /dev/null @@ -1,322 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "https://github.com/googleapis/python-talent.git", - "sha": "12d77fa03a5b4757e74c40f5aa7d4e60bcebf4c2" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "ef705a6d9fd6dcd8f0b13e012cb284332734785b", - "internalRef": "365856330" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "4501974ad08b5d693311457e2ea4ce845676e329" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "4501974ad08b5d693311457e2ea4ce845676e329" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "talent", - "apiVersion": "v4beta1", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "talent", - "apiVersion": "v4", - "language": "python", - "generator": "bazel" - } - } - ], - "generatedFiles": [ - ".coveragerc", - ".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/header-checker-lint.yml", - ".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-head.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-head.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-head.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples-against-head.sh", - ".kokoro/test-samples-impl.sh", - ".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/company_service.rst", - "docs/talent_v4/completion.rst", - "docs/talent_v4/event_service.rst", - "docs/talent_v4/job_service.rst", - "docs/talent_v4/services.rst", - "docs/talent_v4/tenant_service.rst", - "docs/talent_v4/types.rst", - "docs/talent_v4beta1/application_service.rst", - "docs/talent_v4beta1/company_service.rst", - "docs/talent_v4beta1/completion.rst", - "docs/talent_v4beta1/event_service.rst", - "docs/talent_v4beta1/job_service.rst", - "docs/talent_v4beta1/profile_service.rst", - "docs/talent_v4beta1/services.rst", - "docs/talent_v4beta1/tenant_service.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 From 80c4c8515fbb372a13785bdf9e8529c57fd5e05f Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 12 May 2021 13:11:30 -0400 Subject: [PATCH 09/26] chore: add library type to .repo-metadata.json (#92) --- .repo-metadata.json | 1 + 1 file changed, 1 insertion(+) 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", From 2409dc6fc0fba07e943f2822dce6e1fc19990bf6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 14 May 2021 12:56:11 +0000 Subject: [PATCH 10/26] chore: upgrade gapic-generator-python to 0.46.3 (#98) PiperOrigin-RevId: 373649163 Source-Link: https://github.com/googleapis/googleapis/commit/7e1b14e6c7a9ab96d2db7e4a131981f162446d34 Source-Link: https://github.com/googleapis/googleapis-gen/commit/0a3c7d272d697796db75857bac73905c68e498c3 --- docs/talent_v4/company_service.rst | 1 - docs/talent_v4/job_service.rst | 1 - docs/talent_v4/tenant_service.rst | 1 - docs/talent_v4beta1/application_service.rst | 1 - docs/talent_v4beta1/company_service.rst | 1 - docs/talent_v4beta1/job_service.rst | 1 - docs/talent_v4beta1/profile_service.rst | 1 - docs/talent_v4beta1/tenant_service.rst | 1 - google/cloud/talent/__init__.py | 138 ++-- google/cloud/talent_v4/__init__.py | 33 +- google/cloud/talent_v4/gapic_metadata.json | 299 +++++++ google/cloud/talent_v4/services/__init__.py | 1 - .../services/company_service/__init__.py | 2 - .../services/company_service/async_client.py | 47 +- .../services/company_service/client.py | 84 +- .../services/company_service/pagers.py | 4 +- .../company_service/transports/__init__.py | 2 - .../company_service/transports/base.py | 131 ++- .../company_service/transports/grpc.py | 28 +- .../transports/grpc_asyncio.py | 29 +- .../talent_v4/services/completion/__init__.py | 2 - .../services/completion/async_client.py | 29 +- .../talent_v4/services/completion/client.py | 67 +- .../completion/transports/__init__.py | 2 - .../services/completion/transports/base.py | 107 ++- .../services/completion/transports/grpc.py | 22 +- .../completion/transports/grpc_asyncio.py | 23 +- .../services/event_service/__init__.py | 2 - .../services/event_service/async_client.py | 28 +- .../services/event_service/client.py | 66 +- .../event_service/transports/__init__.py | 2 - .../services/event_service/transports/base.py | 102 ++- .../services/event_service/transports/grpc.py | 22 +- .../event_service/transports/grpc_asyncio.py | 23 +- .../services/job_service/__init__.py | 2 - .../services/job_service/async_client.py | 62 +- .../talent_v4/services/job_service/client.py | 103 +-- .../talent_v4/services/job_service/pagers.py | 4 +- .../job_service/transports/__init__.py | 2 - .../services/job_service/transports/base.py | 161 ++-- .../services/job_service/transports/grpc.py | 42 +- .../job_service/transports/grpc_asyncio.py | 43 +- .../services/tenant_service/__init__.py | 2 - .../services/tenant_service/async_client.py | 47 +- .../services/tenant_service/client.py | 80 +- .../services/tenant_service/pagers.py | 4 +- .../tenant_service/transports/__init__.py | 2 - .../tenant_service/transports/base.py | 131 ++- .../tenant_service/transports/grpc.py | 28 +- .../tenant_service/transports/grpc_asyncio.py | 29 +- google/cloud/talent_v4/types/__init__.py | 2 - google/cloud/talent_v4/types/common.py | 113 +-- google/cloud/talent_v4/types/company.py | 38 +- .../cloud/talent_v4/types/company_service.py | 38 +- .../talent_v4/types/completion_service.py | 29 +- google/cloud/talent_v4/types/event.py | 20 +- google/cloud/talent_v4/types/event_service.py | 7 +- google/cloud/talent_v4/types/filters.py | 79 +- google/cloud/talent_v4/types/histogram.py | 10 +- google/cloud/talent_v4/types/job.py | 91 +-- google/cloud/talent_v4/types/job_service.py | 125 +-- google/cloud/talent_v4/types/tenant.py | 7 +- .../cloud/talent_v4/types/tenant_service.py | 35 +- google/cloud/talent_v4beta1/__init__.py | 47 +- .../cloud/talent_v4beta1/gapic_metadata.json | 437 ++++++++++ .../cloud/talent_v4beta1/services/__init__.py | 1 - .../services/application_service/__init__.py | 2 - .../application_service/async_client.py | 49 +- .../services/application_service/client.py | 94 +-- .../services/application_service/pagers.py | 4 +- .../transports/__init__.py | 2 - .../application_service/transports/base.py | 137 +++- .../application_service/transports/grpc.py | 28 +- .../transports/grpc_asyncio.py | 29 +- .../services/company_service/__init__.py | 2 - .../services/company_service/async_client.py | 43 +- .../services/company_service/client.py | 76 +- .../services/company_service/pagers.py | 4 +- .../company_service/transports/__init__.py | 2 - .../company_service/transports/base.py | 131 ++- .../company_service/transports/grpc.py | 28 +- .../transports/grpc_asyncio.py | 29 +- .../services/completion/__init__.py | 2 - .../services/completion/async_client.py | 29 +- .../services/completion/client.py | 63 +- .../completion/transports/__init__.py | 2 - .../services/completion/transports/base.py | 107 ++- .../services/completion/transports/grpc.py | 22 +- .../completion/transports/grpc_asyncio.py | 23 +- .../services/event_service/__init__.py | 2 - .../services/event_service/async_client.py | 28 +- .../services/event_service/client.py | 66 +- .../event_service/transports/__init__.py | 2 - .../services/event_service/transports/base.py | 102 ++- .../services/event_service/transports/grpc.py | 22 +- .../event_service/transports/grpc_asyncio.py | 23 +- .../services/job_service/__init__.py | 2 - .../services/job_service/async_client.py | 57 +- .../services/job_service/client.py | 95 +-- .../services/job_service/pagers.py | 8 +- .../job_service/transports/__init__.py | 2 - .../services/job_service/transports/base.py | 161 ++-- .../services/job_service/transports/grpc.py | 42 +- .../job_service/transports/grpc_asyncio.py | 43 +- .../services/profile_service/__init__.py | 2 - .../services/profile_service/async_client.py | 49 +- .../services/profile_service/client.py | 86 +- .../services/profile_service/pagers.py | 6 +- .../profile_service/transports/__init__.py | 2 - .../profile_service/transports/base.py | 137 +++- .../profile_service/transports/grpc.py | 28 +- .../transports/grpc_asyncio.py | 29 +- .../services/tenant_service/__init__.py | 2 - .../services/tenant_service/async_client.py | 43 +- .../services/tenant_service/client.py | 76 +- .../services/tenant_service/pagers.py | 4 +- .../tenant_service/transports/__init__.py | 2 - .../tenant_service/transports/base.py | 131 ++- .../tenant_service/transports/grpc.py | 28 +- .../tenant_service/transports/grpc_asyncio.py | 29 +- google/cloud/talent_v4beta1/types/__init__.py | 2 - .../cloud/talent_v4beta1/types/application.py | 52 +- .../types/application_service.py | 35 +- google/cloud/talent_v4beta1/types/batch.py | 1 - google/cloud/talent_v4beta1/types/common.py | 153 ++-- google/cloud/talent_v4beta1/types/company.py | 38 +- .../talent_v4beta1/types/company_service.py | 38 +- .../types/completion_service.py | 29 +- google/cloud/talent_v4beta1/types/event.py | 30 +- .../talent_v4beta1/types/event_service.py | 7 +- google/cloud/talent_v4beta1/types/filters.py | 187 ++--- .../cloud/talent_v4beta1/types/histogram.py | 10 +- google/cloud/talent_v4beta1/types/job.py | 91 +-- .../cloud/talent_v4beta1/types/job_service.py | 131 +-- google/cloud/talent_v4beta1/types/profile.py | 297 +++---- .../talent_v4beta1/types/profile_service.py | 84 +- google/cloud/talent_v4beta1/types/tenant.py | 11 +- .../talent_v4beta1/types/tenant_service.py | 35 +- scripts/fixup_talent_v4_keywords.py | 49 +- scripts/fixup_talent_v4beta1_keywords.py | 71 +- tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/talent_v4/__init__.py | 1 - .../gapic/talent_v4/test_company_service.py | 589 ++++++++------ tests/unit/gapic/talent_v4/test_completion.py | 311 +++++-- .../gapic/talent_v4/test_event_service.py | 341 ++++++-- .../unit/gapic/talent_v4/test_job_service.py | 762 +++++++++-------- .../gapic/talent_v4/test_tenant_service.py | 524 ++++++++---- tests/unit/gapic/talent_v4beta1/__init__.py | 1 - .../test_application_service.py | 569 ++++++++----- .../talent_v4beta1/test_company_service.py | 574 +++++++------ .../gapic/talent_v4beta1/test_completion.py | 312 +++++-- .../talent_v4beta1/test_event_service.py | 341 ++++++-- .../gapic/talent_v4beta1/test_job_service.py | 765 +++++++++--------- .../talent_v4beta1/test_profile_service.py | 601 ++++++++------ .../talent_v4beta1/test_tenant_service.py | 522 ++++++++---- 157 files changed, 7496 insertions(+), 5454 deletions(-) create mode 100644 google/cloud/talent_v4/gapic_metadata.json create mode 100644 google/cloud/talent_v4beta1/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/docs/talent_v4/company_service.rst b/docs/talent_v4/company_service.rst index f850f370..7d9acfc3 100644 --- a/docs/talent_v4/company_service.rst +++ b/docs/talent_v4/company_service.rst @@ -5,7 +5,6 @@ CompanyService :members: :inherited-members: - .. automodule:: google.cloud.talent_v4.services.company_service.pagers :members: :inherited-members: diff --git a/docs/talent_v4/job_service.rst b/docs/talent_v4/job_service.rst index 28d73f01..d8824847 100644 --- a/docs/talent_v4/job_service.rst +++ b/docs/talent_v4/job_service.rst @@ -5,7 +5,6 @@ JobService :members: :inherited-members: - .. automodule:: google.cloud.talent_v4.services.job_service.pagers :members: :inherited-members: diff --git a/docs/talent_v4/tenant_service.rst b/docs/talent_v4/tenant_service.rst index d38c6bcd..26f09b23 100644 --- a/docs/talent_v4/tenant_service.rst +++ b/docs/talent_v4/tenant_service.rst @@ -5,7 +5,6 @@ TenantService :members: :inherited-members: - .. automodule:: google.cloud.talent_v4.services.tenant_service.pagers :members: :inherited-members: diff --git a/docs/talent_v4beta1/application_service.rst b/docs/talent_v4beta1/application_service.rst index 6539e8fd..58e0529b 100644 --- a/docs/talent_v4beta1/application_service.rst +++ b/docs/talent_v4beta1/application_service.rst @@ -5,7 +5,6 @@ ApplicationService :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 index e2050c75..b77843f6 100644 --- a/docs/talent_v4beta1/company_service.rst +++ b/docs/talent_v4beta1/company_service.rst @@ -5,7 +5,6 @@ CompanyService :members: :inherited-members: - .. automodule:: google.cloud.talent_v4beta1.services.company_service.pagers :members: :inherited-members: diff --git a/docs/talent_v4beta1/job_service.rst b/docs/talent_v4beta1/job_service.rst index a78f4f32..605042c2 100644 --- a/docs/talent_v4beta1/job_service.rst +++ b/docs/talent_v4beta1/job_service.rst @@ -5,7 +5,6 @@ JobService :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 index e558ed06..cf00d2d8 100644 --- a/docs/talent_v4beta1/profile_service.rst +++ b/docs/talent_v4beta1/profile_service.rst @@ -5,7 +5,6 @@ ProfileService :members: :inherited-members: - .. automodule:: google.cloud.talent_v4beta1.services.profile_service.pagers :members: :inherited-members: diff --git a/docs/talent_v4beta1/tenant_service.rst b/docs/talent_v4beta1/tenant_service.rst index 4de1dcfe..cc5630b3 100644 --- a/docs/talent_v4beta1/tenant_service.rst +++ b/docs/talent_v4beta1/tenant_service.rst @@ -5,7 +5,6 @@ TenantService :members: :inherited-members: - .. automodule:: google.cloud.talent_v4beta1.services.tenant_service.pagers :members: :inherited-members: 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 b193e4de..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", @@ -144,10 +153,10 @@ "SearchJobsResponse", "SpellingCorrection", "Tenant", + "TenantServiceClient", "TimestampRange", "UpdateCompanyRequest", "UpdateJobRequest", "UpdateTenantRequest", "Visibility", - "TenantServiceClient", ) 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/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 dbb65fa2..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,31 +51,26 @@ 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 @@ -86,7 +78,8 @@ class CompanyServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -101,7 +94,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -118,7 +111,7 @@ 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. @@ -132,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 @@ -169,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, @@ -209,7 +201,6 @@ async def create_company( 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. @@ -240,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: @@ -293,7 +283,6 @@ async def get_company( 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. @@ -324,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 @@ -337,7 +325,8 @@ 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, ), @@ -362,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]] = (), @@ -397,7 +386,6 @@ async def update_company( 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. @@ -428,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: @@ -483,7 +470,6 @@ async def delete_company( 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. @@ -504,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 @@ -517,7 +502,8 @@ 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, ), @@ -562,7 +548,6 @@ async def list_companies( 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. @@ -591,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 @@ -604,7 +588,8 @@ 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, ), diff --git a/google/cloud/talent_v4/services/company_service/client.py b/google/cloud/talent_v4/services/company_service/client.py index 10f6d998..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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -154,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, @@ -179,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, ) @@ -205,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 @@ -216,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 @@ -227,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 @@ -238,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, ) @@ -252,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 @@ -312,9 +312,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -326,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. @@ -346,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: @@ -394,7 +397,6 @@ def create_company( 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. @@ -427,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: @@ -479,7 +479,6 @@ def get_company( 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. @@ -512,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 @@ -540,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]] = (), @@ -575,7 +572,6 @@ def update_company( 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. @@ -608,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: @@ -662,7 +656,6 @@ def delete_company( 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. @@ -685,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 @@ -733,7 +724,6 @@ def list_companies( 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. @@ -764,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 beac2a8b..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 ccaaff88..8bff9984 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,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.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 +37,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class CompanyServiceTransport(abc.ABC): """Abstract transport class for CompanyService.""" @@ -47,21 +57,24 @@ 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, **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,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -120,7 +180,8 @@ 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, ), @@ -137,7 +198,8 @@ 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, ), @@ -151,7 +213,8 @@ 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, ), @@ -163,47 +226,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 fe1e7dd2..b8b64af5 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,7 +51,7 @@ 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, @@ -68,7 +65,8 @@ def __init__( """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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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 + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -306,7 +306,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. @@ -327,7 +327,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 0643fff5..838acfa0 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, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ 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, @@ -112,7 +111,8 @@ def __init__( """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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -314,7 +313,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. @@ -335,7 +334,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 16c1c698..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,25 +45,20 @@ 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 @@ -74,7 +66,8 @@ class CompletionAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -89,7 +82,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -106,7 +99,7 @@ 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. @@ -120,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 @@ -157,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, @@ -180,7 +172,6 @@ async def complete_query( Args: 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. @@ -192,7 +183,6 @@ async def complete_query( 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, @@ -204,7 +194,8 @@ 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, ), diff --git a/google/cloud/talent_v4/services/completion/client.py b/google/cloud/talent_v4/services/completion/client.py index 6eacd4ca..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: @@ -110,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -127,7 +126,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -146,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, @@ -171,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, ) @@ -197,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 @@ -208,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 @@ -219,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 @@ -230,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, ) @@ -244,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 @@ -304,9 +304,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -318,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. @@ -338,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: @@ -369,7 +372,6 @@ def complete_query( Args: 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. @@ -381,7 +383,6 @@ def complete_query( 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 e8fdb64a..799b28c6 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,20 @@ # 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.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 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class CompletionTransport(abc.ABC): """Abstract transport class for Completion.""" @@ -44,21 +54,24 @@ 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, **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,7 +80,7 @@ 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): @@ -81,29 +94,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -114,7 +174,8 @@ 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, ), @@ -126,11 +187,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 7732a1dc..371fc914 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,7 +47,7 @@ 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, @@ -64,7 +61,8 @@ def __init__( """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 @@ -174,7 +172,7 @@ def __init__( 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,13 +203,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **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 d23bd831..8c22b5ec 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, @@ -80,13 +77,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -94,7 +93,7 @@ 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, @@ -108,7 +107,8 @@ def __init__( """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 @@ -166,7 +166,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint 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 c6237025..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,27 +44,22 @@ 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 @@ -75,7 +67,8 @@ class EventServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -90,7 +83,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -107,7 +100,7 @@ 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. @@ -121,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 @@ -158,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, @@ -206,7 +198,6 @@ async def create_client_event( 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. @@ -241,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 9cae6703..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: @@ -111,7 +109,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +127,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -147,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, ) @@ -182,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 @@ -193,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 @@ -204,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 @@ -215,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, ) @@ -229,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 @@ -289,9 +289,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -303,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. @@ -323,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: @@ -379,7 +382,6 @@ def create_client_event( 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. @@ -416,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 5f0f004d..064b5bf4 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,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.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 +35,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class EventServiceTransport(abc.ABC): """Abstract transport class for EventService.""" @@ -45,21 +55,24 @@ 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, **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,7 +81,7 @@ 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): @@ -82,29 +95,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,9 +176,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 05c80ebc..73878a96 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,7 +48,7 @@ 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, @@ -65,7 +62,8 @@ def __init__( """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 @@ -175,7 +173,7 @@ def __init__( 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, @@ -206,13 +204,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **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 302f0083..c1e89c3a 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, @@ -81,13 +78,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -95,7 +94,7 @@ 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, @@ -109,7 +108,8 @@ def __init__( """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 @@ -167,7 +167,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint 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 06bee535..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,25 +57,20 @@ 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 @@ -86,7 +78,8 @@ class JobServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -101,7 +94,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -118,7 +111,7 @@ 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. @@ -132,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 @@ -169,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, @@ -210,7 +202,6 @@ async def create_job( 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. @@ -239,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: @@ -299,7 +289,6 @@ async def batch_create_jobs( 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. @@ -330,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) @@ -390,7 +377,6 @@ async def get_job( 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. @@ -419,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 @@ -432,7 +417,8 @@ 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, ), @@ -457,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]] = (), @@ -491,7 +477,6 @@ async def update_job( 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. @@ -520,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: @@ -580,7 +564,6 @@ async def batch_update_jobs( 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. @@ -611,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) @@ -672,7 +653,6 @@ async def delete_job( 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. @@ -693,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 @@ -706,7 +685,8 @@ 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, ), @@ -766,7 +746,6 @@ async def batch_delete_jobs( 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. @@ -797,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) @@ -885,7 +862,6 @@ async def list_jobs( 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. @@ -914,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: @@ -929,7 +904,8 @@ 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, ), @@ -975,7 +951,6 @@ async def search_jobs( 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. @@ -987,7 +962,6 @@ async def search_jobs( 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, @@ -1036,7 +1010,6 @@ async def search_jobs_for_alert( 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. @@ -1048,7 +1021,6 @@ async def search_jobs_for_alert( 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 8a43c082..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: @@ -120,7 +118,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -137,7 +136,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -156,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, @@ -181,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, @@ -197,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, ) @@ -223,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 @@ -234,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 @@ -245,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 @@ -256,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, ) @@ -270,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 @@ -330,9 +330,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -344,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. @@ -364,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: @@ -413,7 +416,6 @@ def create_job( 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. @@ -444,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: @@ -503,7 +503,6 @@ def batch_create_jobs( 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. @@ -536,10 +535,8 @@ 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 is not None: @@ -594,7 +591,6 @@ def get_job( 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. @@ -625,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 @@ -653,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]] = (), @@ -687,7 +681,6 @@ def update_job( 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. @@ -718,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: @@ -777,7 +768,6 @@ def batch_update_jobs( 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. @@ -810,10 +800,8 @@ 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 is not None: @@ -869,7 +857,6 @@ def delete_job( 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. @@ -892,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 @@ -955,7 +940,6 @@ def batch_delete_jobs( 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. @@ -988,10 +972,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 names is not None: @@ -1074,7 +1056,6 @@ def list_jobs( 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. @@ -1105,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: @@ -1156,7 +1135,6 @@ def search_jobs( 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. @@ -1168,7 +1146,6 @@ def search_jobs( 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 @@ -1218,7 +1195,6 @@ def search_jobs_for_alert( 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. @@ -1230,7 +1206,6 @@ def search_jobs_for_alert( 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 bbef2c82..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 97429e5b..452fb3f5 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,24 @@ # 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.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 +39,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class JobServiceTransport(abc.ABC): """Abstract transport class for JobService.""" @@ -49,21 +59,24 @@ 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, **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,7 +85,7 @@ 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): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -125,7 +185,8 @@ 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, ), @@ -145,7 +206,8 @@ 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, ), @@ -162,7 +224,8 @@ 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, ), @@ -187,84 +250,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() @@ -272,11 +328,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 d80e73f4..3acde84a 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,7 +53,7 @@ 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, @@ -70,7 +67,8 @@ def __init__( """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 @@ -181,7 +179,7 @@ def __init__( 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, @@ -212,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -271,7 +271,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. @@ -290,7 +290,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"] @@ -349,7 +349,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. @@ -368,12 +368,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. @@ -394,14 +394,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. @@ -420,7 +420,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 599527c8..6f75a23b 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, @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ 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, @@ -114,7 +113,8 @@ def __init__( """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 @@ -173,7 +173,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -280,7 +279,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. @@ -300,7 +299,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"] @@ -362,7 +361,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. @@ -382,14 +381,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. @@ -410,7 +409,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"] @@ -418,7 +417,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. @@ -438,7 +437,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 51ebcab7..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,31 +48,26 @@ 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 @@ -83,7 +75,8 @@ class TenantServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -98,7 +91,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -115,7 +108,7 @@ 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. @@ -129,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 @@ -166,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, @@ -205,7 +197,6 @@ async def create_tenant( 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. @@ -237,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: @@ -289,7 +279,6 @@ async def get_tenant( 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. @@ -321,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 @@ -334,7 +322,8 @@ 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, ), @@ -359,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]] = (), @@ -394,7 +383,6 @@ async def update_tenant( 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. @@ -426,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: @@ -478,7 +465,6 @@ async def delete_tenant( 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. @@ -499,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 @@ -512,7 +497,8 @@ 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, ), @@ -556,7 +542,6 @@ async def list_tenants( 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. @@ -585,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 @@ -598,7 +582,8 @@ 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, ), diff --git a/google/cloud/talent_v4/services/tenant_service/client.py b/google/cloud/talent_v4/services/tenant_service/client.py index ef6d560c..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: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -151,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, ) @@ -186,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 @@ -197,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 @@ -208,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 @@ -219,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, ) @@ -233,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 @@ -293,9 +293,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -307,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. @@ -327,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: @@ -374,7 +377,6 @@ def create_tenant( 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. @@ -408,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: @@ -459,7 +459,6 @@ def get_tenant( 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. @@ -493,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 @@ -521,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]] = (), @@ -556,7 +553,6 @@ def update_tenant( 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. @@ -590,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: @@ -641,7 +635,6 @@ def delete_tenant( 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. @@ -664,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 @@ -711,7 +702,6 @@ def list_tenants( 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. @@ -742,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 91d4a213..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 c921d237..074d4307 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,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.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 +37,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TenantServiceTransport(abc.ABC): """Abstract transport class for TenantService.""" @@ -47,21 +57,24 @@ 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, **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,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -120,7 +180,8 @@ 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, ), @@ -137,7 +198,8 @@ 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, ), @@ -151,7 +213,8 @@ 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, ), @@ -163,47 +226,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 d837f65e..75eaec9d 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,7 +51,7 @@ 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, @@ -68,7 +65,8 @@ def __init__( """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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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 + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -304,7 +304,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. @@ -323,7 +323,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 072a50dc..e58a8d87 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, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ 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, @@ -112,7 +111,8 @@ def __init__( """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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -310,7 +309,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. @@ -329,7 +328,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 29719f84..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .common import ( BatchOperationMetadata, CompensationInfo, diff --git a/google/cloud/talent_v4/types/common.py b/google/cloud/talent_v4/types/common.py index 6acd7469..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( @@ -205,7 +202,6 @@ class CommuteMethod(proto.Enum): class TimestampRange(proto.Message): r"""Message representing a period of time between two timestamps. - Attributes: start_time (google.protobuf.timestamp_pb2.Timestamp): Begin of the period (inclusive). @@ -213,9 +209,8 @@ class TimestampRange(proto.Message): 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): @@ -264,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): @@ -348,14 +340,10 @@ class RequestMetadata(proto.Message): 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",) @@ -369,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): @@ -400,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): @@ -455,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 @@ -485,16 +468,13 @@ 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[google.cloud.talent_v4.types.CompensationInfo.CompensationEntry]): Job compensation information. @@ -631,31 +611,28 @@ 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 (google.type.money_pb2.Money): The maximum amount of compensation. If left empty, the value @@ -669,16 +646,17 @@ class CompensationRange(proto.Message): 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, ) @@ -726,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 84df7fe7..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 @@ -99,7 +96,6 @@ class Company(proto.Message): class DerivedInfo(proto.Message): r"""Derived details about the company. - Attributes: headquarters_location (google.cloud.talent_v4.types.Location): A structured headquarters location of the company, resolved @@ -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 c6862175..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 @@ -50,14 +46,12 @@ class CreateCompanyRequest(proto.Message): 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,12 +62,11 @@ 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 (google.cloud.talent_v4.types.Company): Required. The company resource to replace the @@ -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,18 +132,14 @@ 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[google.cloud.talent_v4.types.Company]): Companies for the current client. @@ -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 fe233356..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 @@ -78,24 +74,17 @@ 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[google.cloud.talent_v4.types.CompleteQueryResponse.CompletionResult]): Results of the matching job/company @@ -107,7 +96,6 @@ class CompleteQueryResponse(proto.Message): class CompletionResult(proto.Message): r"""Resource that represents completion results. - Attributes: suggestion (str): The suggestion for the query. @@ -118,18 +106,15 @@ class CompletionResult(proto.Message): [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 40ffe6f2..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( @@ -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): @@ -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 8a328f9a..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 @@ -42,8 +38,7 @@ class CreateClientEventRequest(proto.Message): 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 482632fa..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 @@ -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 @@ -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,7 +280,6 @@ class TelecommutePreference(proto.Enum): class CompensationFilter(proto.Message): r"""Filter on job compensation type and amount. - Attributes: type_ (google.cloud.talent_v4.types.CompensationFilter.FilterType): Required. Type of filter. @@ -325,21 +302,19 @@ 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 (google.cloud.talent_v4.types.CommuteMethod): Required. The method of transportation to @@ -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 ec9484c9..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): @@ -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 2bd27c59..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",},) @@ -313,7 +310,6 @@ class Job(proto.Message): 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,15 +333,12 @@ 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[google.cloud.talent_v4.types.Location]): Structured locations of the job, resolved from @@ -364,14 +357,12 @@ 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 @@ -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 78289bbe..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 @@ -78,14 +74,12 @@ class CreateJobRequest(proto.Message): 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,12 +89,11 @@ 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 (google.cloud.talent_v4.types.Job): Required. The Job to be updated. @@ -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 @@ -189,20 +181,15 @@ class ListJobsRequest(proto.Message): 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[google.cloud.talent_v4.types.Job]): The Jobs for a given company. @@ -220,15 +207,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. @@ -579,49 +563,34 @@ 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[google.cloud.talent_v4.types.SearchJobsResponse.MatchingJob]): The Job entities that match the specified @@ -693,20 +662,15 @@ class MatchingJob(proto.Message): """ 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 (google.cloud.talent_v4.types.Location): Location used as the destination in the @@ -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 @@ -767,14 +722,12 @@ class BatchCreateJobsRequest(proto.Message): 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 @@ -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,14 +791,12 @@ 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 (google.cloud.talent_v4.types.Job): Here [Job][google.cloud.talent.v4.Job] only contains basic @@ -865,8 +815,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,) class BatchCreateJobsResponse(proto.Message): 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 be5e4d8d..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 @@ -50,14 +46,12 @@ class CreateTenantRequest(proto.Message): 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,12 +60,11 @@ 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 (google.cloud.talent_v4.types.Tenant): Required. The tenant resource to replace the @@ -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,16 +120,13 @@ 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[google.cloud.talent_v4.types.Tenant]): Tenants for the current client. @@ -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 4743ac58..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", @@ -244,6 +257,7 @@ "SpellingCorrection", "SummarizedProfile", "Tenant", + "TenantServiceClient", "TimeFilter", "TimestampRange", "UpdateApplicationRequest", @@ -253,5 +267,4 @@ "UpdateTenantRequest", "Visibility", "WorkExperienceFilter", - "TenantServiceClient", ) 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/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 6c6bb683..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,31 +59,26 @@ 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 @@ -94,7 +86,8 @@ class ApplicationServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -109,7 +102,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -126,7 +119,7 @@ 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. @@ -141,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 @@ -178,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, @@ -220,7 +212,6 @@ async def create_application( 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. @@ -247,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: @@ -300,7 +290,6 @@ async def get_application( 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. @@ -327,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 @@ -340,7 +328,8 @@ 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, ), @@ -383,7 +372,6 @@ async def update_application( 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. @@ -410,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 @@ -462,7 +449,6 @@ async def delete_application( 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. @@ -483,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 @@ -496,7 +481,8 @@ 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, ), @@ -541,7 +527,6 @@ async def list_applications( 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. @@ -571,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 @@ -584,7 +568,8 @@ 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, ), diff --git a/google/cloud/talent_v4beta1/services/application_service/client.py b/google/cloud/talent_v4beta1/services/application_service/client.py index f93ebd01..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: @@ -122,7 +120,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -139,7 +138,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -158,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 @@ -169,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, @@ -185,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, @@ -201,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, @@ -217,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, @@ -233,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, ) @@ -246,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 @@ -257,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 @@ -268,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 @@ -279,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, ) @@ -293,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 @@ -353,9 +353,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -367,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. @@ -387,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: @@ -437,7 +440,6 @@ def create_application( 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. @@ -466,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: @@ -518,7 +518,6 @@ def get_application( 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. @@ -547,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 @@ -593,7 +590,6 @@ def update_application( 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. @@ -622,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 @@ -673,7 +667,6 @@ def delete_application( 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. @@ -696,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 @@ -744,7 +735,6 @@ def list_applications( 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. @@ -776,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 1aa9124c..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 9667920d..6e8230fe 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,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.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 +37,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ApplicationServiceTransport(abc.ABC): """Abstract transport class for ApplicationService.""" @@ -47,21 +57,24 @@ 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, **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,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -120,7 +180,8 @@ 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, ), @@ -137,7 +198,8 @@ 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, ), @@ -151,7 +213,8 @@ 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, ), @@ -163,53 +226,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 e47f721b..e2eb0eed 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,7 +51,7 @@ 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, @@ -68,7 +65,8 @@ def __init__( """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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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 + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -310,7 +310,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. @@ -329,7 +329,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 95164149..ee0502d9 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, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ 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, @@ -112,7 +111,8 @@ def __init__( """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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -319,7 +318,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. @@ -339,7 +338,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 30a4dfff..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,31 +48,26 @@ 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 @@ -83,7 +75,8 @@ class CompanyServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -98,7 +91,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -115,7 +108,7 @@ 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. @@ -129,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 @@ -166,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, @@ -208,7 +200,6 @@ async def create_company( 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. @@ -239,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: @@ -295,7 +285,6 @@ async def get_company( 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. @@ -326,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 @@ -339,7 +327,8 @@ 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, ), @@ -382,7 +371,6 @@ async def update_company( 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. @@ -413,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 @@ -469,7 +456,6 @@ async def delete_company( 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. @@ -490,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 @@ -503,7 +488,8 @@ 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, ), @@ -551,7 +537,6 @@ async def list_companies( 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. @@ -580,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 @@ -593,7 +577,8 @@ 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, ), diff --git a/google/cloud/talent_v4beta1/services/company_service/client.py b/google/cloud/talent_v4beta1/services/company_service/client.py index aa2572b5..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: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -153,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, @@ -178,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, ) @@ -191,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 @@ -202,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 @@ -213,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 @@ -224,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, ) @@ -238,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 @@ -298,9 +298,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -312,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. @@ -332,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: @@ -382,7 +385,6 @@ def create_company( 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. @@ -415,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: @@ -470,7 +470,6 @@ def get_company( 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. @@ -503,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 @@ -549,7 +546,6 @@ def update_company( 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. @@ -582,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 @@ -637,7 +631,6 @@ def delete_company( 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. @@ -660,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 @@ -711,7 +702,6 @@ def list_companies( 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. @@ -742,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 cb04a126..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 e4af061a..32ffd8fe 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,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.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 +37,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class CompanyServiceTransport(abc.ABC): """Abstract transport class for CompanyService.""" @@ -47,21 +57,24 @@ 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, **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,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -120,7 +180,8 @@ 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, ), @@ -137,7 +198,8 @@ 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, ), @@ -151,7 +213,8 @@ 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, ), @@ -163,47 +226,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 b1d479f5..88044b80 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,7 +51,7 @@ 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, @@ -68,7 +65,8 @@ def __init__( """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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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 + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -306,7 +306,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. @@ -327,7 +327,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 70bdce4b..91bdd6fa 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, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ 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, @@ -112,7 +111,8 @@ def __init__( """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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -314,7 +313,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. @@ -335,7 +334,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 194a7b7e..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,25 +43,20 @@ 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 @@ -72,7 +64,8 @@ class CompletionAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -87,7 +80,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -104,7 +97,7 @@ 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. @@ -118,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 @@ -155,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, @@ -178,7 +170,6 @@ async def complete_query( Args: 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. @@ -190,7 +181,6 @@ async def complete_query( 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, @@ -202,7 +192,8 @@ 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, ), diff --git a/google/cloud/talent_v4beta1/services/completion/client.py b/google/cloud/talent_v4beta1/services/completion/client.py index 780d7342..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: @@ -110,7 +108,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -127,7 +126,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -146,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, @@ -171,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, ) @@ -184,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 @@ -195,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 @@ -206,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 @@ -217,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, ) @@ -231,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 @@ -291,9 +291,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -305,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. @@ -325,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: @@ -356,7 +359,6 @@ def complete_query( Args: 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. @@ -368,7 +370,6 @@ def complete_query( 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 fb7aaee0..1f49c232 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,20 @@ # 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.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 +34,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class CompletionTransport(abc.ABC): """Abstract transport class for Completion.""" @@ -44,21 +54,24 @@ 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, **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,7 +80,7 @@ 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): @@ -81,29 +94,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -114,7 +174,8 @@ 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, ), @@ -126,11 +187,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 164a4e5d..1886e170 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,7 +47,7 @@ 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, @@ -64,7 +61,8 @@ def __init__( """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 @@ -174,7 +172,7 @@ def __init__( 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,13 +203,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **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 88a6a731..7df7ee5a 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, @@ -80,13 +77,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -94,7 +93,7 @@ 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, @@ -108,7 +107,8 @@ def __init__( """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 @@ -166,7 +166,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint 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 4bddf1e1..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,27 +44,22 @@ 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 @@ -75,7 +67,8 @@ class EventServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -90,7 +83,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -107,7 +100,7 @@ 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. @@ -121,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 @@ -158,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, @@ -208,7 +200,6 @@ async def create_client_event( 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. @@ -243,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 b231a98d..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: @@ -111,7 +109,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +127,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -147,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, @@ -172,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, ) @@ -185,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 @@ -196,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 @@ -207,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 @@ -218,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, ) @@ -232,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 @@ -292,9 +292,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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 +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. @@ -326,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: @@ -384,7 +387,6 @@ def create_client_event( 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. @@ -421,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 0fdd167b..edf4dd0f 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,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.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 +35,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class EventServiceTransport(abc.ABC): """Abstract transport class for EventService.""" @@ -45,21 +55,24 @@ 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, **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,7 +81,7 @@ 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): @@ -82,29 +95,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,9 +176,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 18186207..c0669a2b 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,7 +48,7 @@ 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, @@ -65,7 +62,8 @@ def __init__( """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 @@ -175,7 +173,7 @@ def __init__( 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, @@ -206,13 +204,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **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 687b2763..347587fc 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, @@ -81,13 +78,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -95,7 +94,7 @@ 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, @@ -109,7 +108,8 @@ def __init__( """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 @@ -167,7 +167,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint 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 9f758a33..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,25 +53,20 @@ 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 @@ -82,7 +74,8 @@ class JobServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -97,7 +90,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -114,7 +107,7 @@ 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. @@ -128,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 @@ -165,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, @@ -208,7 +200,6 @@ async def create_job( 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. @@ -237,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: @@ -296,7 +286,6 @@ async def batch_create_jobs( 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. @@ -328,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) @@ -391,7 +378,6 @@ async def get_job( 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. @@ -420,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 @@ -433,7 +418,8 @@ 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, ), @@ -475,7 +461,6 @@ async def update_job( 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. @@ -504,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 @@ -561,7 +545,6 @@ async def batch_update_jobs( 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. @@ -593,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) @@ -657,7 +638,6 @@ async def delete_job( 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. @@ -678,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 @@ -691,7 +670,8 @@ 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, ), @@ -756,7 +736,6 @@ async def batch_delete_jobs( 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. @@ -777,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: @@ -857,7 +835,6 @@ async def list_jobs( 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. @@ -886,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: @@ -901,7 +877,8 @@ 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, ), @@ -947,7 +924,6 @@ async def search_jobs( 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. @@ -963,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, @@ -1018,7 +993,6 @@ async def search_jobs_for_alert( 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. @@ -1034,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 d044dc14..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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -154,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, @@ -179,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, @@ -195,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, ) @@ -208,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 @@ -219,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 @@ -230,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 @@ -241,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, ) @@ -255,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 @@ -315,9 +315,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -329,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. @@ -349,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: @@ -400,7 +403,6 @@ def create_job( 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. @@ -431,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: @@ -489,7 +489,6 @@ def batch_create_jobs( 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. @@ -523,10 +522,8 @@ 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 is not None: @@ -584,7 +581,6 @@ def get_job( 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. @@ -615,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 @@ -660,7 +654,6 @@ def update_job( 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. @@ -691,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 @@ -747,7 +738,6 @@ def batch_update_jobs( 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. @@ -781,10 +771,8 @@ 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 is not None: @@ -843,7 +831,6 @@ def delete_job( 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. @@ -866,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 @@ -934,7 +919,6 @@ def batch_delete_jobs( 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. @@ -957,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: @@ -1036,7 +1018,6 @@ def list_jobs( 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. @@ -1067,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: @@ -1118,7 +1097,6 @@ def search_jobs( 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. @@ -1134,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 @@ -1190,7 +1167,6 @@ def search_jobs_for_alert( 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. @@ -1206,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 47d07398..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -246,7 +244,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -374,7 +372,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 5cb1997b..12c5fac1 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,24 @@ # 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.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 +39,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class JobServiceTransport(abc.ABC): """Abstract transport class for JobService.""" @@ -49,21 +59,24 @@ 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, **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,7 +85,7 @@ 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): @@ -86,29 +99,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -125,7 +185,8 @@ 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, ), @@ -145,7 +206,8 @@ 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, ), @@ -162,7 +224,8 @@ 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, ), @@ -187,84 +250,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() @@ -272,11 +328,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 188b42a6..85ecd085 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,7 +53,7 @@ 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, @@ -70,7 +67,8 @@ def __init__( """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 @@ -181,7 +179,7 @@ def __init__( 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, @@ -212,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -271,7 +271,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. @@ -290,7 +290,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"] @@ -349,7 +349,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. @@ -368,12 +368,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. @@ -394,14 +394,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 @@ -421,7 +421,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 4896073b..5d7613c6 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, @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ 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, @@ -114,7 +113,8 @@ def __init__( """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 @@ -173,7 +173,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -280,7 +279,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. @@ -300,7 +299,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"] @@ -362,7 +361,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. @@ -382,14 +381,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. @@ -410,14 +409,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 @@ -437,7 +436,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 7c581cb8..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,31 +53,26 @@ 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 @@ -88,7 +80,8 @@ class ProfileServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -103,7 +96,7 @@ def from_service_account_info(cls, info: dict, *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 +113,7 @@ 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. @@ -134,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 @@ -171,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, @@ -204,7 +196,6 @@ async def list_profiles( 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. @@ -233,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 @@ -246,7 +236,8 @@ 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, ), @@ -303,7 +294,6 @@ async def create_profile( 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. @@ -332,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: @@ -382,7 +371,6 @@ async def get_profile( 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. @@ -411,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 @@ -424,7 +411,8 @@ 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, ), @@ -464,7 +452,6 @@ async def update_profile( 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. @@ -493,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 @@ -545,7 +531,6 @@ async def delete_profile( 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. @@ -566,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 @@ -579,7 +563,8 @@ 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, ), @@ -620,7 +605,6 @@ async def search_profiles( 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. @@ -636,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 eb27801d..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: @@ -120,7 +118,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -137,7 +136,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -156,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, @@ -181,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, ) @@ -207,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 @@ -218,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 @@ -229,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 @@ -240,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, ) @@ -254,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 @@ -314,9 +314,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -328,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. @@ -348,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: @@ -389,7 +392,6 @@ def list_profiles( 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. @@ -420,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 @@ -480,7 +480,6 @@ def create_profile( 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. @@ -511,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: @@ -560,7 +557,6 @@ def get_profile( 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. @@ -591,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 @@ -634,7 +628,6 @@ def update_profile( 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. @@ -665,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 @@ -716,7 +707,6 @@ def delete_profile( 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. @@ -739,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 @@ -783,7 +771,6 @@ def search_profiles( 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. @@ -799,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 1793730e..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -247,7 +245,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 3a1c0f76..3320cbfd 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,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.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 +37,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ProfileServiceTransport(abc.ABC): """Abstract transport class for ProfileService.""" @@ -47,21 +57,24 @@ 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, **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,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -117,7 +177,8 @@ 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, ), @@ -134,7 +195,8 @@ 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, ), @@ -151,7 +213,8 @@ 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, ), @@ -166,11 +229,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() @@ -178,47 +241,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 a3dbfe39..fdd944e3 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,7 +51,7 @@ 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, @@ -68,7 +65,8 @@ def __init__( """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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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 + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -335,7 +335,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. @@ -356,7 +356,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 9c405dac..e5fea4ab 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, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ 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, @@ -112,7 +111,8 @@ def __init__( """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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -344,7 +343,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. @@ -365,7 +364,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 047dffe9..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,31 +47,26 @@ 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 @@ -82,7 +74,8 @@ class TenantServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -97,7 +90,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -114,7 +107,7 @@ 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. @@ -128,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 @@ -165,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, @@ -204,7 +196,6 @@ async def create_tenant( 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. @@ -236,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: @@ -288,7 +278,6 @@ async def get_tenant( 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. @@ -320,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 @@ -333,7 +321,8 @@ 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, ), @@ -376,7 +365,6 @@ async def update_tenant( 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. @@ -408,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 @@ -458,7 +445,6 @@ async def delete_tenant( 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. @@ -479,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 @@ -492,7 +477,8 @@ 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, ), @@ -536,7 +522,6 @@ async def list_tenants( 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. @@ -565,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 @@ -578,7 +562,8 @@ 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, ), diff --git a/google/cloud/talent_v4beta1/services/tenant_service/client.py b/google/cloud/talent_v4beta1/services/tenant_service/client.py index e0750d74..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: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *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 @@ -150,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, ) @@ -185,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 @@ -196,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 @@ -207,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 @@ -218,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, ) @@ -232,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 @@ -292,9 +292,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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 +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. @@ -326,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: @@ -373,7 +376,6 @@ def create_tenant( 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. @@ -407,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: @@ -458,7 +458,6 @@ def get_tenant( 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. @@ -492,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 @@ -538,7 +535,6 @@ def update_tenant( 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. @@ -572,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 @@ -621,7 +615,6 @@ def delete_tenant( 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 +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 @@ -691,7 +682,6 @@ def list_tenants( 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. @@ -722,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 5d402971..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 73ae1b06..d61181b5 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,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.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 +37,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TenantServiceTransport(abc.ABC): """Abstract transport class for TenantService.""" @@ -47,21 +57,24 @@ 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, **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,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_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=self._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=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -120,7 +180,8 @@ 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, ), @@ -137,7 +198,8 @@ 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, ), @@ -151,7 +213,8 @@ 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, ), @@ -163,47 +226,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 f187b6c1..e80b73ea 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,7 +51,7 @@ 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, @@ -68,7 +65,8 @@ def __init__( """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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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 + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -304,7 +304,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. @@ -323,7 +323,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 59aa7ff4..1203c8fe 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, @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ 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, @@ -112,7 +111,8 @@ def __init__( """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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -310,7 +309,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. @@ -329,7 +328,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 98bf50a7..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,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .application import Application from .application_service import ( CreateApplicationRequest, diff --git a/google/cloud/talent_v4beta1/types/application.py b/google/cloud/talent_v4beta1/types/application.py index 41eda976..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( @@ -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 81a0bae8..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 @@ -51,8 +47,7 @@ class CreateApplicationRequest(proto.Message): 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,12 +66,11 @@ 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 (google.cloud.talent_v4beta1.types.Application): Required. The application resource to replace @@ -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,16 +133,13 @@ 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[google.cloud.talent_v4beta1.types.Application]): Applications for the current client. @@ -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 3d6d81ba..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( @@ -253,7 +250,6 @@ class AvailabilitySignalType(proto.Enum): class TimestampRange(proto.Message): r"""Message representing a period of time between two timestamps. - Attributes: start_time (google.protobuf.timestamp_pb2.Timestamp): Begin of the period (inclusive). @@ -261,9 +257,8 @@ class TimestampRange(proto.Message): 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): @@ -312,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): @@ -396,14 +388,10 @@ class RequestMetadata(proto.Message): 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",) @@ -417,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): @@ -448,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): @@ -494,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 @@ -522,16 +506,13 @@ 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[google.cloud.talent_v4beta1.types.CompensationInfo.CompensationEntry]): Job compensation information. @@ -668,31 +649,28 @@ 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 (google.type.money_pb2.Money): The maximum amount of compensation. If left empty, the value @@ -706,16 +684,17 @@ class CompensationRange(proto.Message): 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, ) @@ -723,7 +702,6 @@ 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. @@ -741,20 +719,15 @@ 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. @@ -777,20 +750,15 @@ 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 (google.cloud.talent_v4beta1.types.Rating): The rating on this interview. @@ -800,7 +768,6 @@ class Interview(proto.Message): """ rating = proto.Field(proto.MESSAGE, number=6, message="Rating",) - outcome = proto.Field(proto.ENUM, number=7, enum="Outcome",) @@ -821,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): @@ -872,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 ed091608..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 @@ -104,7 +101,6 @@ class Company(proto.Message): class DerivedInfo(proto.Message): r"""Derived details about the company. - Attributes: headquarters_location (google.cloud.talent_v4beta1.types.Location): A structured headquarters location of the company, resolved @@ -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 ab1de2b8..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 @@ -52,14 +48,12 @@ class CreateCompanyRequest(proto.Message): 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,12 +67,11 @@ 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 (google.cloud.talent_v4beta1.types.Company): Required. The company resource to replace the @@ -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,18 +144,14 @@ 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[google.cloud.talent_v4beta1.types.Company]): Companies for the current client. @@ -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 1b53f07e..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 @@ -84,24 +80,17 @@ 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[google.cloud.talent_v4beta1.types.CompleteQueryResponse.CompletionResult]): Results of the matching job/company @@ -113,7 +102,6 @@ class CompleteQueryResponse(proto.Message): class CompletionResult(proto.Message): r"""Resource that represents completion results. - Attributes: suggestion (str): The suggestion for the query. @@ -124,18 +112,15 @@ class CompletionResult(proto.Message): [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 70cec508..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( @@ -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): @@ -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): @@ -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 d389c18f..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 @@ -44,8 +40,7 @@ class CreateClientEventRequest(proto.Message): 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 70f87f90..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 @@ -214,46 +210,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 ProfileQuery(proto.Message): r"""Filters to apply when performing the search query. - Attributes: query (str): Keywords to match any text fields of @@ -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 @@ -682,24 +650,18 @@ 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_ (google.cloud.talent_v4beta1.types.CompensationFilter.FilterType): Required. Type of filter. @@ -722,21 +684,19 @@ 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 (google.cloud.talent_v4beta1.types.CommuteMethod): Required. The method of transportation to @@ -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,14 +776,12 @@ 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 @@ -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", @@ -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): @@ -909,9 +858,12 @@ class WorkExperienceFilter(proto.Message): (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): @@ -937,14 +889,12 @@ class ApplicationDateFilter(proto.Message): 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,16 +933,13 @@ 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 (google.protobuf.timestamp_pb2.Timestamp): Start timestamp, matching profiles with the @@ -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,12 +979,11 @@ 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 (google.cloud.talent_v4beta1.types.AvailabilitySignalType): Required. Type of signal to apply filter on. @@ -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 b809ac0b..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): @@ -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 a378bbd5..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",},) @@ -322,7 +319,6 @@ class Job(proto.Message): 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,15 +342,12 @@ 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[google.cloud.talent_v4beta1.types.Location]): Structured locations of the job, resolved from @@ -373,14 +366,12 @@ 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 @@ -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 8ee4d6fa..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 @@ -77,14 +73,12 @@ class CreateJobRequest(proto.Message): 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,12 +91,11 @@ 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 (google.cloud.talent_v4beta1.types.Job): Required. The Job to be updated. @@ -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 @@ -228,20 +218,15 @@ class ListJobsRequest(proto.Message): 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[google.cloud.talent_v4beta1.types.Job]): The Jobs for a given company. @@ -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. @@ -633,51 +615,35 @@ 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[google.cloud.talent_v4beta1.types.SearchJobsResponse.MatchingJob]): The Job entities that match the specified @@ -758,20 +724,15 @@ class MatchingJob(proto.Message): """ 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 (google.cloud.talent_v4beta1.types.Location): Location used as the destination in the @@ -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 @@ -835,14 +786,12 @@ class BatchCreateJobsRequest(proto.Message): 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 @@ -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): @@ -905,7 +854,6 @@ class JobOperationResult(proto.Message): class JobResult(proto.Message): r"""Mutation result of a job. - Attributes: job (google.cloud.talent_v4beta1.types.Job): Here [Job][google.cloud.talent.v4beta1.Job] only contains @@ -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 33c9a31f..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( @@ -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,7 +355,6 @@ class Profile(proto.Message): class AvailabilitySignal(proto.Message): r"""Candidate availability signal. - Attributes: type_ (google.cloud.talent_v4beta1.types.AvailabilitySignalType): Type of signal. @@ -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 @@ -450,14 +415,12 @@ 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 @@ -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,30 +475,22 @@ 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 (google.cloud.talent_v4beta1.types.ContactInfoUsage): The usage of the address. For example, @@ -556,19 +510,18 @@ class Address(proto.Message): """ 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 (google.cloud.talent_v4beta1.types.ContactInfoUsage): The usage of the email address. For example, @@ -579,13 +532,11 @@ 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 (google.cloud.talent_v4beta1.types.ContactInfoUsage): The usage of the phone. For example, SCHOOL, @@ -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): @@ -661,15 +608,12 @@ 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 (google.type.date_pb2.Date): Start date of the employment. @@ -721,36 +665,27 @@ 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 (google.type.date_pb2.Date): The start date of the education. @@ -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): @@ -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): @@ -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): @@ -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. @@ -999,22 +906,14 @@ class Patent(proto.Message): 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 c64b7c3d..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 @@ -90,20 +86,15 @@ 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[google.cloud.talent_v4beta1.types.Profile]): Profiles for the specific tenant. @@ -119,13 +110,11 @@ 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. @@ -136,14 +125,12 @@ class CreateProfileRequest(proto.Message): 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,12 +140,11 @@ 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 (google.cloud.talent_v4beta1.types.Profile): Required. Profile to be updated. @@ -169,13 +155,13 @@ class UpdateProfileRequest(proto.Message): """ 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,12 +171,11 @@ 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. @@ -426,38 +411,26 @@ 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 @@ -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): @@ -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 c399eba2..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 @@ -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 104c43c7..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 @@ -50,14 +46,12 @@ class CreateTenantRequest(proto.Message): 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,12 +60,11 @@ 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 (google.cloud.talent_v4beta1.types.Tenant): Required. The tenant resource to replace the @@ -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,16 +120,13 @@ 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[google.cloud.talent_v4beta1.types.Tenant]): Tenants for the current client. @@ -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/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/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 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/talent_v4/__init__.py +++ b/tests/unit/gapic/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"); diff --git a/tests/unit/gapic/talent_v4/test_company_service.py b/tests/unit/gapic/talent_v4/test_company_service.py index eaa1a863..c77ebb7e 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,56 @@ 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,] ) def test_company_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -111,7 +140,7 @@ def test_company_service_client_from_service_account_info(client_class): "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: @@ -164,7 +193,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() @@ -452,7 +481,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, @@ -478,43 +507,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 @@ -526,7 +540,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -534,7 +548,6 @@ def test_create_company_empty_call(): client.create_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.CreateCompanyRequest() @@ -543,7 +556,7 @@ 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, @@ -571,42 +584,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 @@ -616,17 +615,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. @@ -641,17 +640,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. @@ -665,13 +666,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( @@ -682,14 +682,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. @@ -703,7 +701,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: @@ -721,15 +721,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. @@ -745,7 +745,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, @@ -771,43 +771,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 @@ -819,7 +804,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -827,7 +812,6 @@ def test_get_company_empty_call(): client.get_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.GetCompanyRequest() @@ -836,7 +820,7 @@ 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, @@ -864,42 +848,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 @@ -909,17 +879,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. @@ -934,17 +904,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. @@ -958,13 +930,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",) @@ -973,12 +944,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. @@ -990,7 +960,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: @@ -1006,13 +978,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. @@ -1026,7 +999,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, @@ -1052,43 +1025,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 @@ -1100,7 +1058,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1108,7 +1066,6 @@ def test_update_company_empty_call(): client.update_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.UpdateCompanyRequest() @@ -1117,7 +1074,7 @@ 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, @@ -1145,42 +1102,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 @@ -1190,17 +1133,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. @@ -1217,17 +1160,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. @@ -1243,32 +1188,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. @@ -1276,13 +1218,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: @@ -1294,22 +1238,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. @@ -1317,7 +1261,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"]), ) @@ -1325,7 +1269,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, @@ -1336,13 +1280,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. @@ -1357,7 +1299,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1365,7 +1307,6 @@ def test_delete_company_empty_call(): client.delete_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.DeleteCompanyRequest() @@ -1374,7 +1315,7 @@ 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, @@ -1385,13 +1326,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. @@ -1404,17 +1343,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. @@ -1429,17 +1368,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. @@ -1453,13 +1394,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",) @@ -1468,12 +1408,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. @@ -1485,7 +1424,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: @@ -1501,13 +1442,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. @@ -1521,7 +1463,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, @@ -1534,19 +1476,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" @@ -1558,7 +1496,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1566,7 +1504,6 @@ def test_list_companies_empty_call(): client.list_companies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.ListCompaniesRequest() @@ -1575,7 +1512,7 @@ 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, @@ -1590,18 +1527,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" @@ -1611,17 +1545,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. @@ -1636,11 +1570,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. @@ -1648,7 +1585,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. @@ -1662,13 +1598,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",) @@ -1677,12 +1612,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. @@ -1694,7 +1628,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: @@ -1712,13 +1648,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. @@ -1729,7 +1666,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: @@ -1763,7 +1700,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: @@ -1789,7 +1726,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( @@ -1822,7 +1759,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( @@ -1853,16 +1790,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( @@ -1872,7 +1809,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( @@ -1883,7 +1820,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 @@ -1892,13 +1829,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 @@ -1913,23 +1850,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", ) @@ -1941,7 +1878,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 @@ -1958,15 +1895,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 = (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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CompanyServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1982,19 +1944,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=( @@ -2005,14 +1984,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", @@ -2022,6 +2031,121 @@ def test_company_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompanyServiceGrpcTransport, grpc_helpers), + (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.CompanyServiceGrpcTransport, grpc_helpers), + (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_company_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompanyServiceGrpcTransport, grpc_helpers), + (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_company_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2030,7 +2154,7 @@ def test_company_service_transport_auth_adc(): ], ) def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2072,7 +2196,7 @@ def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_cl 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" @@ -2080,7 +2204,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" ), @@ -2136,9 +2260,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", @@ -2222,7 +2346,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, ) @@ -2246,7 +2369,6 @@ def test_parse_company_path(): def test_tenant_path(): project = "cuttlefish" tenant = "mussel" - expected = "projects/{project}/tenants/{tenant}".format( project=project, tenant=tenant, ) @@ -2268,7 +2390,6 @@ def test_parse_tenant_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2289,7 +2410,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 @@ -2308,7 +2428,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 @@ -2327,7 +2446,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 @@ -2347,7 +2465,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, ) @@ -2374,7 +2491,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) @@ -2383,6 +2500,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 e4ed8c02..76aa5c8f 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,48 @@ 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 _API_CORE_VERSION +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -83,7 +110,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,]) def test_completion_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -98,7 +125,7 @@ def test_completion_client_from_service_account_info(client_class): @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: @@ -149,7 +176,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() @@ -433,7 +460,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, @@ -444,17 +471,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) @@ -466,7 +490,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -474,7 +498,6 @@ def test_complete_query_empty_call(): client.complete_query() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() @@ -484,7 +507,7 @@ async def test_complete_query_async( 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, @@ -497,13 +520,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. @@ -516,17 +537,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. @@ -541,11 +562,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. @@ -553,7 +575,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. @@ -569,16 +590,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( @@ -588,7 +609,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( @@ -599,7 +620,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 @@ -608,13 +629,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 @@ -626,23 +647,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 = 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", ) @@ -654,7 +675,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 @@ -665,15 +686,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 = (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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CompletionTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -689,19 +735,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=( @@ -712,14 +775,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", @@ -729,12 +816,125 @@ def test_completion_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionGrpcTransport, grpc_helpers), + (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.CompletionGrpcTransport, grpc_helpers), + (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_completion_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionGrpcTransport, grpc_helpers), + (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_completion_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + 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 = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -776,7 +976,7 @@ def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class): 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" @@ -784,7 +984,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" ), @@ -835,9 +1035,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", @@ -918,7 +1118,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, ) @@ -942,7 +1141,6 @@ def test_parse_company_path(): def test_tenant_path(): project = "cuttlefish" tenant = "mussel" - expected = "projects/{project}/tenants/{tenant}".format( project=project, tenant=tenant, ) @@ -964,7 +1162,6 @@ def test_parse_tenant_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -985,7 +1182,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 @@ -1004,7 +1200,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 @@ -1023,7 +1218,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 @@ -1043,7 +1237,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, ) @@ -1070,7 +1263,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) @@ -1079,6 +1272,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 e28dd92b..c8b25148 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,51 @@ 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,]) def test_event_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_event_service_client_from_service_account_info(client_class): @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: @@ -150,7 +179,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() @@ -434,7 +463,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, @@ -452,23 +481,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" @@ -480,7 +503,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -490,7 +513,6 @@ def test_create_client_event_empty_call(): client.create_client_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == event_service.CreateClientEventRequest() @@ -499,7 +521,7 @@ 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, @@ -518,22 +540,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" @@ -543,11 +560,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. @@ -555,7 +573,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. @@ -570,11 +587,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. @@ -582,7 +600,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. @@ -596,7 +613,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( @@ -604,7 +621,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( @@ -616,14 +632,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. @@ -637,7 +651,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( @@ -658,15 +672,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. @@ -681,16 +693,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( @@ -700,7 +712,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( @@ -711,7 +723,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 @@ -720,13 +732,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 @@ -741,23 +753,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 = 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", ) @@ -769,7 +781,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 @@ -780,15 +792,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 = (credentials.AnonymousCredentials(), 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 = (ga_credentials.AnonymousCredentials(), None) transport = transports.EventServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -804,19 +841,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=( @@ -827,14 +881,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", @@ -844,12 +928,127 @@ def test_event_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EventServiceGrpcTransport, grpc_helpers), + (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.EventServiceGrpcTransport, grpc_helpers), + (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_event_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EventServiceGrpcTransport, grpc_helpers), + (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_event_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + 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 = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -891,7 +1090,7 @@ def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_clas 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" @@ -899,7 +1098,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" ), @@ -950,9 +1149,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", @@ -1032,7 +1231,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, ) @@ -1054,7 +1252,6 @@ def test_parse_tenant_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1075,7 +1272,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 @@ -1094,7 +1290,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 @@ -1113,7 +1308,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 @@ -1133,7 +1327,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, ) @@ -1160,7 +1353,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) @@ -1169,6 +1362,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 d0254e33..dee2b9d5 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,27 @@ 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 ( + _API_CORE_VERSION, +) +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 +52,38 @@ 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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -100,7 +129,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,]) def test_job_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_job_service_client_from_service_account_info(client_class): @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: @@ -166,7 +195,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() @@ -448,7 +477,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, @@ -479,55 +508,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" @@ -539,7 +546,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -547,7 +554,6 @@ def test_create_job_empty_call(): client.create_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.CreateJobRequest() @@ -556,7 +562,7 @@ 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, @@ -589,54 +595,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" @@ -646,17 +631,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. @@ -671,17 +656,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. @@ -695,13 +680,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( @@ -712,14 +696,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. @@ -733,7 +715,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: @@ -751,15 +733,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. @@ -775,7 +755,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, @@ -788,13 +768,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. @@ -809,7 +787,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -819,7 +797,6 @@ def test_batch_create_jobs_empty_call(): client.batch_create_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.BatchCreateJobsRequest() @@ -828,7 +805,7 @@ 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, @@ -843,13 +820,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. @@ -862,11 +837,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. @@ -874,7 +850,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. @@ -889,11 +864,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. @@ -903,7 +879,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. @@ -917,7 +892,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( @@ -925,7 +900,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( @@ -936,14 +910,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. @@ -957,7 +929,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( @@ -979,15 +951,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. @@ -1001,7 +971,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, @@ -1032,55 +1002,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" @@ -1092,7 +1040,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1100,7 +1048,6 @@ def test_get_job_empty_call(): client.get_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.GetJobRequest() @@ -1109,7 +1056,7 @@ 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, @@ -1142,54 +1089,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" @@ -1199,17 +1125,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. @@ -1224,17 +1150,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. @@ -1248,13 +1174,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",) @@ -1263,12 +1188,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. @@ -1280,7 +1204,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: @@ -1296,13 +1220,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. @@ -1314,7 +1237,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, @@ -1345,55 +1268,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" @@ -1405,7 +1306,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1413,7 +1314,6 @@ def test_update_job_empty_call(): client.update_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.UpdateJobRequest() @@ -1422,7 +1322,7 @@ 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, @@ -1455,54 +1355,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" @@ -1512,17 +1391,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. @@ -1537,17 +1416,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. @@ -1561,32 +1440,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. @@ -1594,13 +1470,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: @@ -1612,22 +1488,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. @@ -1635,7 +1509,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"]), ) @@ -1643,7 +1517,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, @@ -1656,13 +1530,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. @@ -1677,7 +1549,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1687,7 +1559,6 @@ def test_batch_update_jobs_empty_call(): client.batch_update_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.BatchUpdateJobsRequest() @@ -1696,7 +1567,7 @@ 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, @@ -1711,13 +1582,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. @@ -1730,11 +1599,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. @@ -1742,7 +1612,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. @@ -1757,11 +1626,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. @@ -1771,7 +1641,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. @@ -1785,7 +1654,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( @@ -1793,7 +1662,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( @@ -1804,14 +1672,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. @@ -1825,7 +1691,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( @@ -1847,15 +1713,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. @@ -1869,7 +1733,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, @@ -1880,13 +1744,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. @@ -1901,7 +1763,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1909,7 +1771,6 @@ def test_delete_job_empty_call(): client.delete_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.DeleteJobRequest() @@ -1918,7 +1779,7 @@ 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, @@ -1929,13 +1790,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. @@ -1948,17 +1807,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. @@ -1973,17 +1832,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. @@ -1997,13 +1856,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",) @@ -2012,12 +1870,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. @@ -2029,7 +1886,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: @@ -2045,13 +1902,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. @@ -2065,7 +1921,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, @@ -2078,13 +1934,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. @@ -2099,7 +1953,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2109,7 +1963,6 @@ def test_batch_delete_jobs_empty_call(): client.batch_delete_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.BatchDeleteJobsRequest() @@ -2118,7 +1971,7 @@ 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, @@ -2133,13 +1986,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. @@ -2152,11 +2003,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. @@ -2164,7 +2016,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. @@ -2179,11 +2030,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. @@ -2193,7 +2045,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. @@ -2207,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( @@ -2215,7 +2066,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( @@ -2226,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].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. @@ -2247,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( @@ -2269,15 +2117,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. @@ -2291,7 +2137,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, @@ -2304,19 +2150,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" @@ -2328,7 +2170,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2336,7 +2178,6 @@ def test_list_jobs_empty_call(): client.list_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.ListJobsRequest() @@ -2345,7 +2186,7 @@ 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, @@ -2358,18 +2199,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" @@ -2379,17 +2217,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. @@ -2404,11 +2242,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. @@ -2416,7 +2255,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. @@ -2430,13 +2268,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( @@ -2447,14 +2284,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. @@ -2466,7 +2301,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: @@ -2484,15 +2319,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. @@ -2503,7 +2336,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: @@ -2532,7 +2365,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: @@ -2553,7 +2386,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( @@ -2581,7 +2414,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( @@ -2608,7 +2441,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, @@ -2623,25 +2456,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 @@ -2653,7 +2479,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2661,7 +2487,6 @@ def test_search_jobs_empty_call(): client.search_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.SearchJobsRequest() @@ -2670,7 +2495,7 @@ 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, @@ -2687,22 +2512,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 @@ -2712,17 +2532,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. @@ -2737,11 +2557,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. @@ -2749,7 +2570,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. @@ -2766,7 +2586,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, @@ -2783,25 +2603,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 @@ -2813,7 +2626,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2823,7 +2636,6 @@ def test_search_jobs_for_alert_empty_call(): client.search_jobs_for_alert() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.SearchJobsRequest() @@ -2832,7 +2644,7 @@ 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, @@ -2851,22 +2663,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 @@ -2876,11 +2683,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. @@ -2888,7 +2696,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. @@ -2903,11 +2710,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. @@ -2917,7 +2725,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. @@ -2933,16 +2740,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( @@ -2952,7 +2759,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( @@ -2963,7 +2770,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 @@ -2972,13 +2779,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 @@ -2990,23 +2797,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 = 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", ) @@ -3018,7 +2825,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 @@ -3045,15 +2852,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", ) @@ -3069,19 +2901,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=( @@ -3092,14 +2941,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", @@ -3109,12 +2982,127 @@ def test_job_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.JobServiceGrpcTransport, grpc_helpers), + (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.JobServiceGrpcTransport, grpc_helpers), + (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_job_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.JobServiceGrpcTransport, grpc_helpers), + (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_job_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + 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 = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3156,7 +3144,7 @@ def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class) 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" @@ -3164,7 +3152,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" ), @@ -3215,9 +3203,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", @@ -3296,7 +3284,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 @@ -3309,7 +3297,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 @@ -3324,7 +3312,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, ) @@ -3349,7 +3336,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, ) @@ -3373,7 +3359,6 @@ def test_parse_job_path(): def test_tenant_path(): project = "squid" tenant = "clam" - expected = "projects/{project}/tenants/{tenant}".format( project=project, tenant=tenant, ) @@ -3395,7 +3380,6 @@ def test_parse_tenant_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3416,7 +3400,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 @@ -3435,7 +3418,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 @@ -3454,7 +3436,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 @@ -3474,7 +3455,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, ) @@ -3501,7 +3481,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) @@ -3510,6 +3490,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 64e5cbbb..5704524f 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,53 @@ 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -91,7 +120,7 @@ def test__get_default_mtls_endpoint(): "client_class", [TenantServiceClient, TenantServiceAsyncClient,] ) def test_tenant_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -108,7 +137,7 @@ def test_tenant_service_client_from_service_account_info(client_class): "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: @@ -161,7 +190,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() @@ -449,7 +478,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,21 +491,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" @@ -488,7 +512,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -496,7 +520,6 @@ def test_create_tenant_empty_call(): client.create_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.CreateTenantRequest() @@ -505,7 +528,7 @@ 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, @@ -518,20 +541,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" @@ -541,17 +560,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. @@ -566,17 +585,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. @@ -590,13 +611,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( @@ -607,14 +627,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. @@ -628,7 +646,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: @@ -646,15 +666,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. @@ -670,7 +690,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, @@ -683,21 +703,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" @@ -709,7 +724,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -717,7 +732,6 @@ def test_get_tenant_empty_call(): client.get_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.GetTenantRequest() @@ -726,7 +740,7 @@ 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, @@ -739,20 +753,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" @@ -762,17 +772,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. @@ -787,17 +797,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. @@ -811,13 +823,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",) @@ -826,12 +837,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. @@ -843,7 +853,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: @@ -859,13 +871,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. @@ -879,7 +892,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, @@ -892,21 +905,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" @@ -918,7 +926,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -926,7 +934,6 @@ def test_update_tenant_empty_call(): client.update_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.UpdateTenantRequest() @@ -935,7 +942,7 @@ 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, @@ -948,20 +955,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" @@ -971,17 +974,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. @@ -996,17 +999,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. @@ -1020,32 +1025,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. @@ -1053,13 +1055,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: @@ -1071,22 +1075,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. @@ -1094,7 +1098,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"]), ) @@ -1102,7 +1106,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, @@ -1113,13 +1117,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. @@ -1134,7 +1136,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1142,7 +1144,6 @@ def test_delete_tenant_empty_call(): client.delete_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.DeleteTenantRequest() @@ -1151,7 +1152,7 @@ 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, @@ -1162,13 +1163,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. @@ -1181,17 +1180,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. @@ -1206,17 +1205,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. @@ -1230,13 +1231,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",) @@ -1245,12 +1245,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. @@ -1262,7 +1261,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: @@ -1278,13 +1279,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. @@ -1298,7 +1300,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, @@ -1311,19 +1313,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" @@ -1335,7 +1333,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1343,7 +1341,6 @@ def test_list_tenants_empty_call(): client.list_tenants() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.ListTenantsRequest() @@ -1352,7 +1349,7 @@ 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, @@ -1365,18 +1362,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" @@ -1386,17 +1380,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. @@ -1411,11 +1405,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. @@ -1423,7 +1420,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. @@ -1437,13 +1433,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",) @@ -1452,12 +1447,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. @@ -1469,7 +1463,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: @@ -1487,13 +1483,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. @@ -1504,7 +1501,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: @@ -1538,7 +1535,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: @@ -1564,7 +1561,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( @@ -1597,7 +1594,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( @@ -1628,16 +1625,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( @@ -1647,7 +1644,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( @@ -1658,7 +1655,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 @@ -1667,13 +1664,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 @@ -1688,23 +1685,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", ) @@ -1716,7 +1713,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 @@ -1733,15 +1730,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 = (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_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", ) @@ -1757,19 +1779,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=( @@ -1780,14 +1819,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", @@ -1797,6 +1866,121 @@ def test_tenant_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TenantServiceGrpcTransport, grpc_helpers), + (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.TenantServiceGrpcTransport, grpc_helpers), + (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_tenant_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TenantServiceGrpcTransport, grpc_helpers), + (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_tenant_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1805,7 +1989,7 @@ def test_tenant_service_transport_auth_adc(): ], ) def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1847,7 +2031,7 @@ def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_cla 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" @@ -1855,7 +2039,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" ), @@ -1909,9 +2093,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", @@ -1994,7 +2178,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, ) @@ -2016,7 +2199,6 @@ def test_parse_tenant_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2037,7 +2219,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 @@ -2056,7 +2237,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 @@ -2075,7 +2255,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 @@ -2095,7 +2274,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, ) @@ -2122,7 +2300,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) @@ -2131,6 +2309,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 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/talent_v4beta1/__init__.py +++ b/tests/unit/gapic/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"); diff --git a/tests/unit/gapic/talent_v4beta1/test_application_service.py b/tests/unit/gapic/talent_v4beta1/test_application_service.py index 68c75313..9fb331b0 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,45 @@ ) 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -100,7 +129,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ApplicationServiceClient, ApplicationServiceAsyncClient,] ) def test_application_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -117,7 +146,7 @@ def test_application_service_client_from_service_account_info(client_class): "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: @@ -170,7 +199,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() @@ -468,7 +497,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, @@ -492,37 +521,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" @@ -534,7 +550,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -544,7 +560,6 @@ def test_create_application_empty_call(): client.create_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == application_service.CreateApplicationRequest() @@ -554,7 +569,7 @@ async def test_create_application_async( 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, @@ -580,36 +595,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" @@ -619,11 +622,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. @@ -631,7 +637,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. @@ -647,12 +652,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. @@ -662,7 +668,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. @@ -676,7 +681,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( @@ -684,7 +691,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( @@ -696,14 +702,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. @@ -718,7 +724,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. @@ -742,16 +748,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 @@ -768,7 +772,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, @@ -790,37 +794,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" @@ -832,7 +823,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -840,7 +831,6 @@ def test_get_application_empty_call(): client.get_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == application_service.GetApplicationRequest() @@ -850,7 +840,7 @@ async def test_get_application_async( 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, @@ -874,36 +864,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" @@ -913,17 +891,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. @@ -939,12 +919,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. @@ -952,7 +933,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. @@ -966,13 +946,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",) @@ -981,12 +962,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. @@ -999,7 +981,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. @@ -1018,14 +1000,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 @@ -1040,7 +1021,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, @@ -1064,37 +1045,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" @@ -1106,7 +1074,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1116,7 +1084,6 @@ def test_update_application_empty_call(): client.update_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == application_service.UpdateApplicationRequest() @@ -1126,7 +1093,7 @@ async def test_update_application_async( 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, @@ -1152,36 +1119,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" @@ -1191,11 +1146,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. @@ -1203,7 +1161,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. @@ -1221,12 +1178,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. @@ -1236,7 +1194,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. @@ -1252,7 +1209,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( @@ -1260,7 +1219,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( @@ -1271,12 +1229,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. @@ -1290,7 +1249,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. @@ -1313,14 +1272,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 @@ -1336,7 +1294,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, @@ -1349,13 +1307,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. @@ -1370,7 +1326,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1380,7 +1336,6 @@ def test_delete_application_empty_call(): client.delete_application() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == application_service.DeleteApplicationRequest() @@ -1390,7 +1345,7 @@ async def test_delete_application_async( 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, @@ -1403,13 +1358,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. @@ -1422,11 +1375,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. @@ -1434,7 +1390,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. @@ -1450,12 +1405,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. @@ -1463,7 +1419,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. @@ -1477,7 +1432,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( @@ -1485,7 +1442,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",) @@ -1494,12 +1450,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. @@ -1512,7 +1469,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. @@ -1531,14 +1488,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 @@ -1553,7 +1509,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, @@ -1568,19 +1524,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" @@ -1592,7 +1544,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1602,7 +1554,6 @@ def test_list_applications_empty_call(): client.list_applications() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == application_service.ListApplicationsRequest() @@ -1612,7 +1563,7 @@ async def test_list_applications_async( 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, @@ -1629,18 +1580,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" @@ -1650,11 +1598,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. @@ -1662,7 +1613,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. @@ -1678,12 +1628,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. @@ -1693,7 +1644,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. @@ -1707,7 +1657,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( @@ -1715,7 +1667,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",) @@ -1724,12 +1675,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. @@ -1742,7 +1694,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. @@ -1763,14 +1715,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 @@ -1782,7 +1733,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( @@ -1824,7 +1775,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( @@ -1859,7 +1810,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. @@ -1902,7 +1853,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. @@ -1942,16 +1893,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( @@ -1961,7 +1912,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( @@ -1972,7 +1923,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 @@ -1981,13 +1932,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 @@ -2002,23 +1953,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", ) @@ -2030,7 +1983,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 @@ -2047,15 +2000,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 = (credentials.AnonymousCredentials(), 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 = (ga_credentials.AnonymousCredentials(), None) transport = transports.ApplicationServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2071,19 +2049,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=( @@ -2094,14 +2089,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", @@ -2111,6 +2136,121 @@ def test_application_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ApplicationServiceGrpcTransport, grpc_helpers), + (transports.ApplicationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.ApplicationServiceGrpcTransport, grpc_helpers), + (transports.ApplicationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_application_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ApplicationServiceGrpcTransport, grpc_helpers), + (transports.ApplicationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_application_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2121,7 +2261,7 @@ def test_application_service_transport_auth_adc(): def test_application_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2163,7 +2303,7 @@ def test_application_service_grpc_transport_client_cert_source_for_mtls( 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" @@ -2171,7 +2311,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" ), @@ -2227,9 +2367,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", @@ -2314,7 +2454,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, ) @@ -2342,7 +2481,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, ) @@ -2367,7 +2505,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, ) @@ -2392,7 +2529,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, ) @@ -2415,7 +2551,6 @@ def test_parse_profile_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2436,7 +2571,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 @@ -2455,7 +2589,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 @@ -2474,7 +2607,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 @@ -2494,7 +2626,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, ) @@ -2521,7 +2652,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) @@ -2530,6 +2661,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 973e425a..0fbb0bbe 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,44 @@ 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -96,7 +125,7 @@ def test__get_default_mtls_endpoint(): "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,] ) def test_company_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -113,7 +142,7 @@ def test_company_service_client_from_service_account_info(client_class): "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: @@ -166,7 +195,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() @@ -454,7 +483,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, @@ -480,43 +509,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 @@ -528,7 +542,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -536,7 +550,6 @@ def test_create_company_empty_call(): client.create_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.CreateCompanyRequest() @@ -545,7 +558,7 @@ 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, @@ -573,42 +586,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 @@ -618,17 +617,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. @@ -643,17 +642,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. @@ -667,13 +668,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( @@ -684,14 +684,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. @@ -705,7 +703,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: @@ -723,15 +723,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. @@ -747,7 +747,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, @@ -773,43 +773,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 @@ -821,7 +806,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -829,7 +814,6 @@ def test_get_company_empty_call(): client.get_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.GetCompanyRequest() @@ -838,7 +822,7 @@ 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, @@ -866,42 +850,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 @@ -911,17 +881,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. @@ -936,17 +906,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. @@ -960,13 +932,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",) @@ -975,12 +946,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. @@ -992,7 +962,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: @@ -1008,13 +980,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. @@ -1028,7 +1001,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, @@ -1054,43 +1027,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 @@ -1102,7 +1060,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1110,7 +1068,6 @@ def test_update_company_empty_call(): client.update_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.UpdateCompanyRequest() @@ -1119,7 +1076,7 @@ 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, @@ -1147,42 +1104,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 @@ -1192,17 +1135,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. @@ -1219,17 +1162,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. @@ -1245,13 +1190,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"),) @@ -1260,12 +1204,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. @@ -1278,7 +1221,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: @@ -1296,13 +1241,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. @@ -1317,7 +1263,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, @@ -1328,13 +1274,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. @@ -1349,7 +1293,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1357,7 +1301,6 @@ def test_delete_company_empty_call(): client.delete_company() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.DeleteCompanyRequest() @@ -1366,7 +1309,7 @@ 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, @@ -1377,13 +1320,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. @@ -1396,17 +1337,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. @@ -1421,17 +1362,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. @@ -1445,13 +1388,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",) @@ -1460,12 +1402,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. @@ -1477,7 +1418,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: @@ -1493,13 +1436,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. @@ -1513,7 +1457,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, @@ -1526,19 +1470,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" @@ -1550,7 +1490,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1558,7 +1498,6 @@ def test_list_companies_empty_call(): client.list_companies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == company_service.ListCompaniesRequest() @@ -1567,7 +1506,7 @@ 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, @@ -1582,18 +1521,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" @@ -1603,17 +1539,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. @@ -1628,11 +1564,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. @@ -1640,7 +1579,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. @@ -1654,13 +1592,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",) @@ -1669,12 +1606,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. @@ -1686,7 +1622,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: @@ -1704,13 +1642,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. @@ -1721,7 +1660,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: @@ -1755,7 +1694,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: @@ -1781,7 +1720,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( @@ -1814,7 +1753,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( @@ -1845,16 +1784,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( @@ -1864,7 +1803,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( @@ -1875,7 +1814,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 @@ -1884,13 +1823,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 @@ -1905,23 +1844,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", ) @@ -1933,7 +1872,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 @@ -1950,15 +1889,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 = (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_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", ) @@ -1974,19 +1938,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=( @@ -1997,14 +1978,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", @@ -2014,6 +2025,121 @@ def test_company_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompanyServiceGrpcTransport, grpc_helpers), + (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.CompanyServiceGrpcTransport, grpc_helpers), + (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_company_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompanyServiceGrpcTransport, grpc_helpers), + (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_company_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2022,7 +2148,7 @@ def test_company_service_transport_auth_adc(): ], ) def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2064,7 +2190,7 @@ def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_cl 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" @@ -2072,7 +2198,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" ), @@ -2128,9 +2254,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", @@ -2214,7 +2340,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, ) @@ -2237,7 +2362,6 @@ def test_parse_company_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2258,7 +2382,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 @@ -2277,7 +2400,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 @@ -2296,7 +2418,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 @@ -2316,7 +2437,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, ) @@ -2343,7 +2463,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) @@ -2352,6 +2472,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 48f3e828..1c2b8fb1 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,50 @@ 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -83,7 +112,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,]) def test_completion_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -98,7 +127,7 @@ def test_completion_client_from_service_account_info(client_class): @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: @@ -149,7 +178,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() @@ -433,7 +462,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, @@ -444,17 +473,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) @@ -466,7 +492,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -474,7 +500,6 @@ def test_complete_query_empty_call(): client.complete_query() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() @@ -484,7 +509,7 @@ async def test_complete_query_async( 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, @@ -497,13 +522,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. @@ -516,17 +539,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. @@ -541,11 +564,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. @@ -553,7 +577,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. @@ -569,16 +592,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( @@ -588,7 +611,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( @@ -599,7 +622,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 @@ -608,13 +631,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 @@ -626,23 +649,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 = 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", ) @@ -654,7 +677,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 @@ -665,15 +688,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", ) @@ -689,19 +737,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=( @@ -712,14 +777,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", @@ -729,12 +818,125 @@ def test_completion_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionGrpcTransport, grpc_helpers), + (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.CompletionGrpcTransport, grpc_helpers), + (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_completion_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CompletionGrpcTransport, grpc_helpers), + (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_completion_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + 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 = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -776,7 +978,7 @@ def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class): 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" @@ -784,7 +986,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" ), @@ -835,9 +1037,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", @@ -918,7 +1120,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, ) @@ -941,7 +1142,6 @@ def test_parse_company_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -962,7 +1162,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 @@ -981,7 +1180,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 @@ -1000,7 +1198,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 @@ -1020,7 +1217,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, ) @@ -1047,7 +1243,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) @@ -1056,6 +1252,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 16e25afe..50a09ce8 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,51 @@ 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,]) def test_event_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_event_service_client_from_service_account_info(client_class): @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: @@ -150,7 +179,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() @@ -434,7 +463,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, @@ -452,23 +481,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" @@ -480,7 +503,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -490,7 +513,6 @@ def test_create_client_event_empty_call(): client.create_client_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == event_service.CreateClientEventRequest() @@ -499,7 +521,7 @@ 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, @@ -518,22 +540,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" @@ -543,11 +560,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. @@ -555,7 +573,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. @@ -570,11 +587,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. @@ -582,7 +600,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. @@ -596,7 +613,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( @@ -604,7 +621,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( @@ -616,14 +632,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. @@ -637,7 +651,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( @@ -658,15 +672,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. @@ -681,16 +693,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( @@ -700,7 +712,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( @@ -711,7 +723,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 @@ -720,13 +732,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 @@ -741,23 +753,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 = 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", ) @@ -769,7 +781,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 @@ -780,15 +792,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 = (credentials.AnonymousCredentials(), 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 = (ga_credentials.AnonymousCredentials(), None) transport = transports.EventServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -804,19 +841,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=( @@ -827,14 +881,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", @@ -844,12 +928,127 @@ def test_event_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EventServiceGrpcTransport, grpc_helpers), + (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.EventServiceGrpcTransport, grpc_helpers), + (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_event_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EventServiceGrpcTransport, grpc_helpers), + (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_event_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + 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 = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -891,7 +1090,7 @@ def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_clas 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" @@ -899,7 +1098,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" ), @@ -950,9 +1149,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", @@ -1033,7 +1232,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, ) @@ -1056,7 +1254,6 @@ def test_parse_company_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1077,7 +1274,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 @@ -1096,7 +1292,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 @@ -1115,7 +1310,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 @@ -1135,7 +1329,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, ) @@ -1162,7 +1355,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) @@ -1171,6 +1364,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 db29e42b..bb88f711 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,27 @@ 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 ( + _API_CORE_VERSION, +) +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 +52,38 @@ 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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -100,7 +129,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,]) def test_job_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_job_service_client_from_service_account_info(client_class): @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: @@ -166,7 +195,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() @@ -448,7 +477,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, @@ -479,55 +508,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" @@ -539,7 +546,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -547,7 +554,6 @@ def test_create_job_empty_call(): client.create_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.CreateJobRequest() @@ -556,7 +562,7 @@ 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, @@ -589,54 +595,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" @@ -646,17 +631,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. @@ -671,17 +656,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. @@ -695,13 +680,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( @@ -712,14 +696,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. @@ -733,7 +715,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: @@ -751,15 +733,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. @@ -775,7 +755,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, @@ -788,13 +768,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. @@ -809,7 +787,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -819,7 +797,6 @@ def test_batch_create_jobs_empty_call(): client.batch_create_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.BatchCreateJobsRequest() @@ -828,7 +805,7 @@ 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, @@ -843,13 +820,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. @@ -862,11 +837,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. @@ -874,7 +850,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. @@ -889,11 +864,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. @@ -903,7 +879,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. @@ -917,7 +892,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( @@ -925,7 +900,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( @@ -936,14 +910,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. @@ -957,7 +929,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( @@ -979,15 +951,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. @@ -1001,7 +971,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, @@ -1032,55 +1002,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" @@ -1092,7 +1040,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1100,7 +1048,6 @@ def test_get_job_empty_call(): client.get_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.GetJobRequest() @@ -1109,7 +1056,7 @@ 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, @@ -1142,54 +1089,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" @@ -1199,17 +1125,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. @@ -1224,17 +1150,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. @@ -1248,13 +1174,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",) @@ -1263,12 +1188,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. @@ -1280,7 +1204,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: @@ -1296,13 +1220,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. @@ -1314,7 +1237,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, @@ -1345,55 +1268,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" @@ -1405,7 +1306,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1413,7 +1314,6 @@ def test_update_job_empty_call(): client.update_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.UpdateJobRequest() @@ -1422,7 +1322,7 @@ 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, @@ -1455,54 +1355,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" @@ -1512,17 +1391,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. @@ -1537,17 +1416,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. @@ -1561,13 +1440,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"),) @@ -1576,12 +1454,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. @@ -1593,7 +1470,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: @@ -1609,13 +1486,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. @@ -1629,7 +1505,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, @@ -1642,13 +1518,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. @@ -1663,7 +1537,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1673,7 +1547,6 @@ def test_batch_update_jobs_empty_call(): client.batch_update_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.BatchUpdateJobsRequest() @@ -1682,7 +1555,7 @@ 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, @@ -1697,13 +1570,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. @@ -1716,11 +1587,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. @@ -1728,7 +1600,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. @@ -1743,11 +1614,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. @@ -1757,7 +1629,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. @@ -1771,7 +1642,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( @@ -1779,7 +1650,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( @@ -1790,14 +1660,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. @@ -1811,7 +1679,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( @@ -1833,15 +1701,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. @@ -1855,7 +1721,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, @@ -1866,13 +1732,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. @@ -1887,7 +1751,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1895,7 +1759,6 @@ def test_delete_job_empty_call(): client.delete_job() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.DeleteJobRequest() @@ -1904,7 +1767,7 @@ 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, @@ -1915,13 +1778,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. @@ -1934,17 +1795,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. @@ -1959,17 +1820,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. @@ -1983,13 +1844,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",) @@ -1998,12 +1858,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. @@ -2015,7 +1874,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: @@ -2031,13 +1890,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. @@ -2051,7 +1909,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, @@ -2064,13 +1922,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. @@ -2085,7 +1941,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2095,7 +1951,6 @@ def test_batch_delete_jobs_empty_call(): client.batch_delete_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.BatchDeleteJobsRequest() @@ -2104,7 +1959,7 @@ 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, @@ -2117,13 +1972,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. @@ -2136,11 +1989,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. @@ -2148,7 +2002,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. @@ -2163,11 +2016,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. @@ -2175,7 +2029,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. @@ -2189,7 +2042,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( @@ -2197,7 +2050,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( @@ -2208,14 +2060,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. @@ -2229,7 +2079,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( @@ -2249,15 +2099,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. @@ -2271,7 +2119,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, @@ -2284,19 +2132,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" @@ -2308,7 +2152,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2316,7 +2160,6 @@ def test_list_jobs_empty_call(): client.list_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.ListJobsRequest() @@ -2325,7 +2168,7 @@ 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, @@ -2338,18 +2181,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" @@ -2359,17 +2199,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. @@ -2384,11 +2224,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. @@ -2396,7 +2237,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. @@ -2410,13 +2250,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( @@ -2427,14 +2266,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. @@ -2446,7 +2283,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: @@ -2464,15 +2301,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. @@ -2483,7 +2318,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: @@ -2512,7 +2347,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: @@ -2533,7 +2368,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( @@ -2561,7 +2396,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( @@ -2588,7 +2423,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, @@ -2604,25 +2439,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 @@ -2634,7 +2462,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2642,7 +2470,6 @@ def test_search_jobs_empty_call(): client.search_jobs() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.SearchJobsRequest() @@ -2651,7 +2478,7 @@ 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, @@ -2669,24 +2496,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 @@ -2696,17 +2517,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. @@ -2721,11 +2542,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. @@ -2733,7 +2555,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. @@ -2747,7 +2568,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: @@ -2791,7 +2612,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: @@ -2825,7 +2646,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( @@ -2868,7 +2689,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( @@ -2908,7 +2729,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, @@ -2926,25 +2747,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 @@ -2956,7 +2770,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2966,7 +2780,6 @@ def test_search_jobs_for_alert_empty_call(): client.search_jobs_for_alert() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == job_service.SearchJobsRequest() @@ -2975,7 +2788,7 @@ 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, @@ -2995,24 +2808,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 @@ -3022,11 +2829,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. @@ -3034,7 +2842,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. @@ -3049,11 +2856,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. @@ -3063,7 +2871,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. @@ -3077,7 +2884,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( @@ -3123,7 +2930,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( @@ -3159,7 +2966,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( @@ -3204,7 +3011,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( @@ -3245,16 +3052,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( @@ -3264,7 +3071,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( @@ -3275,7 +3082,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 @@ -3284,13 +3091,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 @@ -3302,23 +3109,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 = 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", ) @@ -3330,7 +3137,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 @@ -3357,15 +3164,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", ) @@ -3381,19 +3213,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=( @@ -3404,14 +3253,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", @@ -3421,12 +3294,127 @@ def test_job_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.JobServiceGrpcTransport, grpc_helpers), + (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.JobServiceGrpcTransport, grpc_helpers), + (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_job_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.JobServiceGrpcTransport, grpc_helpers), + (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_job_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + 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 = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3468,7 +3456,7 @@ def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class) 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" @@ -3476,7 +3464,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" ), @@ -3527,9 +3515,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", @@ -3608,7 +3596,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 @@ -3621,7 +3609,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 @@ -3636,7 +3624,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, ) @@ -3661,7 +3648,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, ) @@ -3684,7 +3670,6 @@ def test_parse_job_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3705,7 +3690,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 @@ -3724,7 +3708,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 @@ -3743,7 +3726,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 @@ -3763,7 +3745,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, ) @@ -3790,7 +3771,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) @@ -3799,6 +3780,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 843a00c4..29edbff5 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,12 @@ 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 ( + _API_CORE_VERSION, +) +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 +50,37 @@ 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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -102,7 +131,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ProfileServiceClient, ProfileServiceAsyncClient,] ) def test_profile_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -119,7 +148,7 @@ def test_profile_service_client_from_service_account_info(client_class): "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: @@ -172,7 +201,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() @@ -460,7 +489,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, @@ -473,19 +502,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" @@ -497,7 +522,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -505,7 +530,6 @@ def test_list_profiles_empty_call(): client.list_profiles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == profile_service.ListProfilesRequest() @@ -514,7 +538,7 @@ 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, @@ -529,18 +553,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" @@ -550,17 +571,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. @@ -575,11 +596,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. @@ -587,7 +611,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. @@ -601,13 +624,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",) @@ -616,12 +638,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. @@ -633,7 +654,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: @@ -651,13 +674,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. @@ -668,7 +692,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: @@ -702,7 +726,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: @@ -728,7 +752,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( @@ -761,7 +785,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( @@ -793,7 +817,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, @@ -814,35 +838,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" @@ -854,7 +866,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -862,7 +874,6 @@ def test_create_profile_empty_call(): client.create_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == profile_service.CreateProfileRequest() @@ -871,7 +882,7 @@ 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, @@ -894,34 +905,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" @@ -931,17 +931,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. @@ -956,17 +956,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. @@ -980,13 +982,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( @@ -997,14 +998,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. @@ -1018,7 +1017,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: @@ -1036,15 +1037,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. @@ -1060,7 +1061,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, @@ -1081,35 +1082,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" @@ -1121,7 +1110,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1129,7 +1118,6 @@ def test_get_profile_empty_call(): client.get_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == profile_service.GetProfileRequest() @@ -1138,7 +1126,7 @@ 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, @@ -1161,34 +1149,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" @@ -1198,17 +1175,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. @@ -1223,17 +1200,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. @@ -1247,13 +1226,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",) @@ -1262,12 +1240,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. @@ -1279,7 +1256,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: @@ -1295,13 +1274,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. @@ -1315,7 +1295,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, @@ -1336,35 +1316,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" @@ -1376,7 +1344,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1384,7 +1352,6 @@ def test_update_profile_empty_call(): client.update_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == profile_service.UpdateProfileRequest() @@ -1393,7 +1360,7 @@ 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, @@ -1416,34 +1383,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" @@ -1453,17 +1409,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. @@ -1480,17 +1436,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. @@ -1506,13 +1464,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"),) @@ -1521,12 +1478,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. @@ -1539,7 +1495,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: @@ -1557,13 +1515,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. @@ -1578,7 +1537,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, @@ -1589,13 +1548,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. @@ -1610,7 +1567,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1618,7 +1575,6 @@ def test_delete_profile_empty_call(): client.delete_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == profile_service.DeleteProfileRequest() @@ -1627,7 +1583,7 @@ 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, @@ -1638,13 +1594,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. @@ -1657,17 +1611,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. @@ -1682,17 +1636,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. @@ -1706,13 +1662,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",) @@ -1721,12 +1676,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. @@ -1738,7 +1692,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: @@ -1754,13 +1710,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. @@ -1774,7 +1731,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, @@ -1789,23 +1746,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" @@ -1817,7 +1768,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1825,7 +1776,6 @@ def test_search_profiles_empty_call(): client.search_profiles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == profile_service.SearchProfilesRequest() @@ -1834,7 +1784,7 @@ 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, @@ -1851,22 +1801,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" @@ -1876,17 +1821,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. @@ -1901,11 +1846,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. @@ -1913,7 +1861,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. @@ -1927,7 +1874,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: @@ -1971,7 +1918,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: @@ -2007,7 +1954,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( @@ -2050,7 +1997,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( @@ -2091,16 +2038,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( @@ -2110,7 +2057,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( @@ -2121,7 +2068,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 @@ -2130,13 +2077,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 @@ -2151,23 +2098,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", ) @@ -2179,7 +2126,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 @@ -2197,15 +2144,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", ) @@ -2221,19 +2193,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=( @@ -2244,14 +2233,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", @@ -2261,6 +2280,121 @@ def test_profile_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProfileServiceGrpcTransport, grpc_helpers), + (transports.ProfileServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.ProfileServiceGrpcTransport, grpc_helpers), + (transports.ProfileServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_profile_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProfileServiceGrpcTransport, grpc_helpers), + (transports.ProfileServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_profile_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2269,7 +2403,7 @@ def test_profile_service_transport_auth_adc(): ], ) def test_profile_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2311,7 +2445,7 @@ def test_profile_service_grpc_transport_client_cert_source_for_mtls(transport_cl 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" @@ -2319,7 +2453,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" ), @@ -2375,9 +2509,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", @@ -2461,7 +2595,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, ) @@ -2485,7 +2618,6 @@ def test_parse_profile_path(): def test_tenant_path(): project = "cuttlefish" tenant = "mussel" - expected = "projects/{project}/tenants/{tenant}".format( project=project, tenant=tenant, ) @@ -2507,7 +2639,6 @@ def test_parse_tenant_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2528,7 +2659,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 @@ -2547,7 +2677,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 @@ -2566,7 +2695,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 @@ -2586,7 +2714,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, ) @@ -2613,7 +2740,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) @@ -2622,6 +2749,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 e4e6acc6..f5dc15fc 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,53 @@ 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 ( + _API_CORE_VERSION, +) +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-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -91,7 +120,7 @@ def test__get_default_mtls_endpoint(): "client_class", [TenantServiceClient, TenantServiceAsyncClient,] ) def test_tenant_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -108,7 +137,7 @@ def test_tenant_service_client_from_service_account_info(client_class): "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: @@ -161,7 +190,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() @@ -449,7 +478,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, @@ -467,25 +496,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" ] @@ -499,7 +521,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -507,7 +529,6 @@ def test_create_tenant_empty_call(): client.create_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.CreateTenantRequest() @@ -516,7 +537,7 @@ 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, @@ -536,24 +557,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" ] @@ -565,17 +580,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. @@ -590,17 +605,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. @@ -614,13 +631,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( @@ -631,14 +647,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. @@ -652,7 +666,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: @@ -670,15 +686,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. @@ -694,7 +710,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, @@ -712,25 +728,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" ] @@ -744,7 +753,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -752,7 +761,6 @@ def test_get_tenant_empty_call(): client.get_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.GetTenantRequest() @@ -761,7 +769,7 @@ 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, @@ -781,24 +789,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" ] @@ -810,17 +812,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. @@ -835,17 +837,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. @@ -859,13 +863,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",) @@ -874,12 +877,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. @@ -891,7 +893,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: @@ -907,13 +911,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. @@ -927,7 +932,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, @@ -945,25 +950,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" ] @@ -977,7 +975,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -985,7 +983,6 @@ def test_update_tenant_empty_call(): client.update_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.UpdateTenantRequest() @@ -994,7 +991,7 @@ 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, @@ -1014,24 +1011,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" ] @@ -1043,17 +1034,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. @@ -1068,17 +1059,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. @@ -1092,13 +1085,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"),) @@ -1107,12 +1099,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. @@ -1125,7 +1116,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: @@ -1143,13 +1136,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. @@ -1164,7 +1158,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, @@ -1175,13 +1169,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. @@ -1196,7 +1188,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1204,7 +1196,6 @@ def test_delete_tenant_empty_call(): client.delete_tenant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.DeleteTenantRequest() @@ -1213,7 +1204,7 @@ 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, @@ -1224,13 +1215,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. @@ -1243,17 +1232,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. @@ -1268,17 +1257,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. @@ -1292,13 +1283,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",) @@ -1307,12 +1297,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. @@ -1324,7 +1313,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: @@ -1340,13 +1331,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. @@ -1360,7 +1352,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, @@ -1373,19 +1365,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" @@ -1397,7 +1385,7 @@ 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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1405,7 +1393,6 @@ def test_list_tenants_empty_call(): client.list_tenants() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == tenant_service.ListTenantsRequest() @@ -1414,7 +1401,7 @@ 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, @@ -1427,18 +1414,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" @@ -1448,17 +1432,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. @@ -1473,11 +1457,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. @@ -1485,7 +1472,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. @@ -1499,13 +1485,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",) @@ -1514,12 +1499,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. @@ -1531,7 +1515,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: @@ -1549,13 +1535,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. @@ -1566,7 +1553,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: @@ -1600,7 +1587,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: @@ -1626,7 +1613,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( @@ -1659,7 +1646,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( @@ -1690,16 +1677,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( @@ -1709,7 +1696,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( @@ -1720,7 +1707,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 @@ -1729,13 +1716,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 @@ -1750,23 +1737,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", ) @@ -1778,7 +1765,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 @@ -1795,15 +1782,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 = (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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TenantServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1819,19 +1831,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=( @@ -1842,14 +1871,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", @@ -1859,6 +1918,121 @@ def test_tenant_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TenantServiceGrpcTransport, grpc_helpers), + (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +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,grpc_helpers", + [ + (transports.TenantServiceGrpcTransport, grpc_helpers), + (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_tenant_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "jobs.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/jobs", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TenantServiceGrpcTransport, grpc_helpers), + (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_tenant_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1867,7 +2041,7 @@ def test_tenant_service_transport_auth_adc(): ], ) def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1909,7 +2083,7 @@ def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_cla 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" @@ -1917,7 +2091,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" ), @@ -1971,9 +2145,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", @@ -2056,7 +2230,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, ) @@ -2078,7 +2251,6 @@ def test_parse_tenant_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2099,7 +2271,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 @@ -2118,7 +2289,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 @@ -2137,7 +2307,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 @@ -2157,7 +2326,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, ) @@ -2184,7 +2352,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) @@ -2193,6 +2361,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) From c00ab5750a4062b7de24fcba5798171be174f131 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Fri, 14 May 2021 19:08:06 -0600 Subject: [PATCH 11/26] fix(deps): add packaging requirement (#99) Add packaging requirement. packaging.version is used for a version comparison in transports/base.py https://github.com/googleapis/python-talent/blob/2409dc6fc0fba07e943f2822dce6e1fc19990bf6/google/cloud/talent_v4/services/job_service/transports/base.py#L18 --- setup.py | 1 + testing/constraints-3.6.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/setup.py b/setup.py index 1dc00641..290ff778 100644 --- a/setup.py +++ b/setup.py @@ -31,6 +31,7 @@ dependencies = [ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.15.0", + "packaging >= 14.3", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index cc205f2a..29486a27 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,3 +7,4 @@ # Then this file should have foo==1.14.0 google-api-core==1.22.2 proto-plus==1.15.0 +packaging==14.3 From 083e37e6d90d7ae33a25c515a9b78b6e63b55cfb Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sun, 16 May 2021 13:46:01 +0000 Subject: [PATCH 12/26] chore: new owl bot post processor docker image (#100) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa --- .github/.OwlBot.lock.yaml | 5 ++--- .pre-commit-config.yaml | 2 +- CONTRIBUTING.rst | 16 +--------------- noxfile.py | 14 ++------------ 4 files changed, 6 insertions(+), 31 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 29084e8a..864c1765 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,3 @@ docker: - digest: sha256:cfc0e802701262c211703c468874d767f65dabe6a1a71d0e07bfc8a3d5175f32 - image: gcr.io/repo-automation-bots/owlbot-python:latest - + image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b5..4f00c7cf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.2 hooks: - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 89f4d56d..1c900d9d 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests 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 diff --git a/noxfile.py b/noxfile.py index 6e8aafb9..c5a826dc 100644 --- a/noxfile.py +++ b/noxfile.py @@ -62,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, @@ -131,9 +124,6 @@ def system(session): # 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") From 7293c8a8e79413609c3e66d7a0d3c99d84e83c02 Mon Sep 17 00:00:00 2001 From: "google-cloud-policy-bot[bot]" <80869356+google-cloud-policy-bot[bot]@users.noreply.github.com> Date: Sun, 16 May 2021 13:50:02 +0000 Subject: [PATCH 13/26] chore: add SECURITY.md (#89) chore: add SECURITY.md --- SECURITY.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 SECURITY.md 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. From b570bf10425166b3703a4c6ed1e3d18c57c7f64d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 22 May 2021 09:18:24 +0000 Subject: [PATCH 14/26] chore: new owl bot post processor docker image (#104) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:3c3a445b3ddc99ccd5d31edc4b4519729635d20693900db32c4f587ed51f7479 --- .github/.OwlBot.lock.yaml | 2 +- noxfile.py | 6 ++++-- samples/snippets/noxfile.py | 8 +++++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 864c1765..46e3f021 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:4c981a6b6f2b8914a448d7b3a01688365be03e3ed26dfee399a6aa77fb112eaa + digest: sha256:3c3a445b3ddc99ccd5d31edc4b4519729635d20693900db32c4f587ed51f7479 diff --git a/noxfile.py b/noxfile.py index c5a826dc..e09739cc 100644 --- a/noxfile.py +++ b/noxfile.py @@ -179,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( @@ -201,7 +201,9 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - session.install("sphinx", "alabaster", "recommonmark", "gcp-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/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 956cdf4f..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': {}, @@ -170,6 +173,9 @@ 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"): if os.path.exists("constraints.txt"): From 64a11fef9747ae2941e80b00861b09b6b608f7ae Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 27 May 2021 19:08:02 +0000 Subject: [PATCH 15/26] chore: new owl bot post processor docker image (#105) gcr.io/repo-automation-bots/owlbot-python:latest@sha256:0856ca711da1fd5ec9d6d7da6c50aa0bbf550fb94acb47b55159a640791987bf --- .github/.OwlBot.lock.yaml | 2 +- docs/multiprocessing.rst | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 46e3f021..127c2cdf 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:3c3a445b3ddc99ccd5d31edc4b4519729635d20693900db32c4f587ed51f7479 + digest: sha256:0856ca711da1fd5ec9d6d7da6c50aa0bbf550fb94acb47b55159a640791987bf 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`. From c8dcabe1cd44b32945f7c2736643c4220ade87a1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 28 May 2021 15:48:04 +0000 Subject: [PATCH 16/26] chore: new owl bot post processor docker image (#106) Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 --- .github/.OwlBot.lock.yaml | 2 +- docs/conf.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 127c2cdf..4ef44149 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:0856ca711da1fd5ec9d6d7da6c50aa0bbf550fb94acb47b55159a640791987bf + digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index 77a0276d..013a849a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -363,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), } From 62df3014cf13125087f367db30a3b1407d47ea50 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 2 Jun 2021 05:30:44 -0400 Subject: [PATCH 17/26] chore: delete unused protos (#103) --- google/cloud/talent_v4/proto/common.proto | 860 ------------- google/cloud/talent_v4/proto/company.proto | 115 -- .../talent_v4/proto/company_service.proto | 187 --- .../talent_v4/proto/completion_service.proto | 154 --- google/cloud/talent_v4/proto/event.proto | 171 --- .../cloud/talent_v4/proto/event_service.proto | 70 -- google/cloud/talent_v4/proto/filters.proto | 338 ------ google/cloud/talent_v4/proto/histogram.proto | 52 - google/cloud/talent_v4/proto/job.proto | 342 ------ .../cloud/talent_v4/proto/job_service.proto | 865 ------------- google/cloud/talent_v4/proto/tenant.proto | 52 - .../talent_v4/proto/tenant_service.proto | 176 --- .../talent_v4beta1/proto/application.proto | 183 --- .../proto/application_service.proto | 181 --- google/cloud/talent_v4beta1/proto/batch.proto | 25 - .../cloud/talent_v4beta1/proto/common.proto | 1073 ----------------- .../cloud/talent_v4beta1/proto/company.proto | 119 -- .../proto/company_service.proto | 214 ---- .../proto/completion_service.proto | 163 --- google/cloud/talent_v4beta1/proto/event.proto | 234 ---- .../talent_v4beta1/proto/event_service.proto | 75 -- .../cloud/talent_v4beta1/proto/filters.proto | 780 ------------ .../talent_v4beta1/proto/histogram.proto | 53 - google/cloud/talent_v4beta1/proto/job.proto | 350 ------ .../talent_v4beta1/proto/job_service.proto | 910 -------------- .../cloud/talent_v4beta1/proto/profile.proto | 783 ------------ .../proto/profile_service.proto | 467 ------- .../cloud/talent_v4beta1/proto/tenant.proto | 81 -- .../talent_v4beta1/proto/tenant_service.proto | 176 --- 29 files changed, 9249 deletions(-) delete mode 100644 google/cloud/talent_v4/proto/common.proto delete mode 100644 google/cloud/talent_v4/proto/company.proto delete mode 100644 google/cloud/talent_v4/proto/company_service.proto delete mode 100644 google/cloud/talent_v4/proto/completion_service.proto delete mode 100644 google/cloud/talent_v4/proto/event.proto delete mode 100644 google/cloud/talent_v4/proto/event_service.proto delete mode 100644 google/cloud/talent_v4/proto/filters.proto delete mode 100644 google/cloud/talent_v4/proto/histogram.proto delete mode 100644 google/cloud/talent_v4/proto/job.proto delete mode 100644 google/cloud/talent_v4/proto/job_service.proto delete mode 100644 google/cloud/talent_v4/proto/tenant.proto delete mode 100644 google/cloud/talent_v4/proto/tenant_service.proto delete mode 100644 google/cloud/talent_v4beta1/proto/application.proto delete mode 100644 google/cloud/talent_v4beta1/proto/application_service.proto delete mode 100644 google/cloud/talent_v4beta1/proto/batch.proto delete mode 100644 google/cloud/talent_v4beta1/proto/common.proto delete mode 100644 google/cloud/talent_v4beta1/proto/company.proto delete mode 100644 google/cloud/talent_v4beta1/proto/company_service.proto delete mode 100644 google/cloud/talent_v4beta1/proto/completion_service.proto delete mode 100644 google/cloud/talent_v4beta1/proto/event.proto delete mode 100644 google/cloud/talent_v4beta1/proto/event_service.proto delete mode 100644 google/cloud/talent_v4beta1/proto/filters.proto delete mode 100644 google/cloud/talent_v4beta1/proto/histogram.proto delete mode 100644 google/cloud/talent_v4beta1/proto/job.proto delete mode 100644 google/cloud/talent_v4beta1/proto/job_service.proto delete mode 100644 google/cloud/talent_v4beta1/proto/profile.proto delete mode 100644 google/cloud/talent_v4beta1/proto/profile_service.proto delete mode 100644 google/cloud/talent_v4beta1/proto/tenant.proto delete mode 100644 google/cloud/talent_v4beta1/proto/tenant_service.proto 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_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; -} From 3145bb8e1d5679ddeb2f35febd4a29f1f2bd7ada Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 16 Jun 2021 15:14:02 +0200 Subject: [PATCH 18/26] chore(deps): update dependency pytest to v6.2.4 (#93) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [pytest](https://docs.pytest.org/en/latest/) ([source](https://togithub.com/pytest-dev/pytest), [changelog](https://docs.pytest.org/en/stable/changelog.html)) | `==6.0.1` -> `==6.2.4` | [![age](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/compatibility-slim/6.0.1)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/pypi/pytest/6.2.4/confidence-slim/6.0.1)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
pytest-dev/pytest ### [`v6.2.4`](https://togithub.com/pytest-dev/pytest/releases/6.2.4) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.3...6.2.4) # pytest 6.2.4 (2021-05-04) ## Bug Fixes - [#​8539](https://togithub.com/pytest-dev/pytest/issues/8539): Fixed assertion rewriting on Python 3.10. ### [`v6.2.3`](https://togithub.com/pytest-dev/pytest/releases/6.2.3) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.2...6.2.3) # pytest 6.2.3 (2021-04-03) ## Bug Fixes - [#​8414](https://togithub.com/pytest-dev/pytest/issues/8414): pytest used to create directories under `/tmp` with world-readable permissions. This means that any user in the system was able to read information written by tests in temporary directories (such as those created by the `tmp_path`/`tmpdir` fixture). Now the directories are created with private permissions. pytest used silenty use a pre-existing `/tmp/pytest-of-` directory, even if owned by another user. This means another user could pre-create such a directory and gain control of another user's temporary directory. Now such a condition results in an error. ### [`v6.2.2`](https://togithub.com/pytest-dev/pytest/releases/6.2.2) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.1...6.2.2) # pytest 6.2.2 (2021-01-25) ## Bug Fixes - [#​8152](https://togithub.com/pytest-dev/pytest/issues/8152): Fixed "(\)" being shown as a skip reason in the verbose test summary line when the reason is empty. - [#​8249](https://togithub.com/pytest-dev/pytest/issues/8249): Fix the `faulthandler` plugin for occasions when running with `twisted.logger` and using `pytest --capture=no`. ### [`v6.2.1`](https://togithub.com/pytest-dev/pytest/releases/6.2.1) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.2.0...6.2.1) # pytest 6.2.1 (2020-12-15) ## Bug Fixes - [#​7678](https://togithub.com/pytest-dev/pytest/issues/7678): Fixed bug where `ImportPathMismatchError` would be raised for files compiled in the host and loaded later from an UNC mounted path (Windows). - [#​8132](https://togithub.com/pytest-dev/pytest/issues/8132): Fixed regression in `approx`: in 6.2.0 `approx` no longer raises `TypeError` when dealing with non-numeric types, falling back to normal comparison. Before 6.2.0, array types like tf.DeviceArray fell through to the scalar case, and happened to compare correctly to a scalar if they had only one element. After 6.2.0, these types began failing, because they inherited neither from standard Python number hierarchy nor from `numpy.ndarray`. `approx` now converts arguments to `numpy.ndarray` if they expose the array protocol and are not scalars. This treats array-like objects like numpy arrays, regardless of size. ### [`v6.2.0`](https://togithub.com/pytest-dev/pytest/releases/6.2.0) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.1.2...6.2.0) # pytest 6.2.0 (2020-12-12) ## Breaking Changes - [#​7808](https://togithub.com/pytest-dev/pytest/issues/7808): pytest now supports python3.6+ only. ## Deprecations - [#​7469](https://togithub.com/pytest-dev/pytest/issues/7469): Directly constructing/calling the following classes/functions is now deprecated: - `_pytest.cacheprovider.Cache` - `_pytest.cacheprovider.Cache.for_config()` - `_pytest.cacheprovider.Cache.clear_cache()` - `_pytest.cacheprovider.Cache.cache_dir_from_config()` - `_pytest.capture.CaptureFixture` - `_pytest.fixtures.FixtureRequest` - `_pytest.fixtures.SubRequest` - `_pytest.logging.LogCaptureFixture` - `_pytest.pytester.Pytester` - `_pytest.pytester.Testdir` - `_pytest.recwarn.WarningsRecorder` - `_pytest.recwarn.WarningsChecker` - `_pytest.tmpdir.TempPathFactory` - `_pytest.tmpdir.TempdirFactory` These have always been considered private, but now issue a deprecation warning, which may become a hard error in pytest 7.0.0. - [#​7530](https://togithub.com/pytest-dev/pytest/issues/7530): The `--strict` command-line option has been deprecated, use `--strict-markers` instead. We have plans to maybe in the future to reintroduce `--strict` and make it an encompassing flag for all strictness related options (`--strict-markers` and `--strict-config` at the moment, more might be introduced in the future). - [#​7988](https://togithub.com/pytest-dev/pytest/issues/7988): The `@pytest.yield_fixture` decorator/function is now deprecated. Use pytest.fixture instead. `yield_fixture` has been an alias for `fixture` for a very long time, so can be search/replaced safely. ## Features - [#​5299](https://togithub.com/pytest-dev/pytest/issues/5299): pytest now warns about unraisable exceptions and unhandled thread exceptions that occur in tests on Python>=3.8. See unraisable for more information. - [#​7425](https://togithub.com/pytest-dev/pytest/issues/7425): New pytester fixture, which is identical to testdir but its methods return pathlib.Path when appropriate instead of `py.path.local`. This is part of the movement to use pathlib.Path objects internally, in order to remove the dependency to `py` in the future. Internally, the old Testdir <\_pytest.pytester.Testdir> is now a thin wrapper around Pytester <\_pytest.pytester.Pytester>, preserving the old interface. - [#​7695](https://togithub.com/pytest-dev/pytest/issues/7695): A new hook was added, pytest_markeval_namespace which should return a dictionary. This dictionary will be used to augment the "global" variables available to evaluate skipif/xfail/xpass markers. Pseudo example `conftest.py`: ```{.sourceCode .python} def pytest_markeval_namespace(): return {"color": "red"} ``` `test_func.py`: ```{.sourceCode .python} @​pytest.mark.skipif("color == 'blue'", reason="Color is not red") def test_func(): assert False ``` - [#​8006](https://togithub.com/pytest-dev/pytest/issues/8006): It is now possible to construct a ~pytest.MonkeyPatch object directly as `pytest.MonkeyPatch()`, in cases when the monkeypatch fixture cannot be used. Previously some users imported it from the private \_pytest.monkeypatch.MonkeyPatch namespace. Additionally, MonkeyPatch.context \ is now a classmethod, and can be used as `with MonkeyPatch.context() as mp: ...`. This is the recommended way to use `MonkeyPatch` directly, since unlike the `monkeypatch` fixture, an instance created directly is not `undo()`-ed automatically. ## Improvements - [#​1265](https://togithub.com/pytest-dev/pytest/issues/1265): Added an `__str__` implementation to the ~pytest.pytester.LineMatcher class which is returned from `pytester.run_pytest().stdout` and similar. It returns the entire output, like the existing `str()` method. - [#​2044](https://togithub.com/pytest-dev/pytest/issues/2044): Verbose mode now shows the reason that a test was skipped in the test's terminal line after the "SKIPPED", "XFAIL" or "XPASS". - [#​7469](https://togithub.com/pytest-dev/pytest/issues/7469) The types of builtin pytest fixtures are now exported so they may be used in type annotations of test functions. The newly-exported types are: - `pytest.FixtureRequest` for the request fixture. - `pytest.Cache` for the cache fixture. - `pytest.CaptureFixture[str]` for the capfd and capsys fixtures. - `pytest.CaptureFixture[bytes]` for the capfdbinary and capsysbinary fixtures. - `pytest.LogCaptureFixture` for the caplog fixture. - `pytest.Pytester` for the pytester fixture. - `pytest.Testdir` for the testdir fixture. - `pytest.TempdirFactory` for the tmpdir_factory fixture. - `pytest.TempPathFactory` for the tmp_path_factory fixture. - `pytest.MonkeyPatch` for the monkeypatch fixture. - `pytest.WarningsRecorder` for the recwarn fixture. Constructing them is not supported (except for MonkeyPatch); they are only meant for use in type annotations. Doing so will emit a deprecation warning, and may become a hard-error in pytest 7.0. Subclassing them is also not supported. This is not currently enforced at runtime, but is detected by type-checkers such as mypy. - [#​7527](https://togithub.com/pytest-dev/pytest/issues/7527): When a comparison between namedtuple \ instances of the same type fails, pytest now shows the differing field names (possibly nested) instead of their indexes. - [#​7615](https://togithub.com/pytest-dev/pytest/issues/7615): Node.warn <\_pytest.nodes.Node.warn> now permits any subclass of Warning, not just PytestWarning \. - [#​7701](https://togithub.com/pytest-dev/pytest/issues/7701): Improved reporting when using `--collected-only`. It will now show the number of collected tests in the summary stats. - [#​7710](https://togithub.com/pytest-dev/pytest/issues/7710): Use strict equality comparison for non-numeric types in pytest.approx instead of raising TypeError. This was the undocumented behavior before 3.7, but is now officially a supported feature. - [#​7938](https://togithub.com/pytest-dev/pytest/issues/7938): New `--sw-skip` argument which is a shorthand for `--stepwise-skip`. - [#​8023](https://togithub.com/pytest-dev/pytest/issues/8023): Added `'node_modules'` to default value for norecursedirs. - [#​8032](https://togithub.com/pytest-dev/pytest/issues/8032): doClassCleanups \ (introduced in unittest in Python and 3.8) is now called appropriately. ## Bug Fixes - [#​4824](https://togithub.com/pytest-dev/pytest/issues/4824): Fixed quadratic behavior and improved performance of collection of items using autouse fixtures and xunit fixtures. - [#​7758](https://togithub.com/pytest-dev/pytest/issues/7758): Fixed an issue where some files in packages are getting lost from `--lf` even though they contain tests that failed. Regressed in pytest 5.4.0. - [#​7911](https://togithub.com/pytest-dev/pytest/issues/7911): Directories created by by tmp_path and tmpdir are now considered stale after 3 days without modification (previous value was 3 hours) to avoid deleting directories still in use in long running test suites. - [#​7913](https://togithub.com/pytest-dev/pytest/issues/7913): Fixed a crash or hang in pytester.spawn <\_pytest.pytester.Pytester.spawn> when the readline module is involved. - [#​7951](https://togithub.com/pytest-dev/pytest/issues/7951): Fixed handling of recursive symlinks when collecting tests. - [#​7981](https://togithub.com/pytest-dev/pytest/issues/7981): Fixed symlinked directories not being followed during collection. Regressed in pytest 6.1.0. - [#​8016](https://togithub.com/pytest-dev/pytest/issues/8016): Fixed only one doctest being collected when using `pytest --doctest-modules path/to/an/__init__.py`. ## Improved Documentation - [#​7429](https://togithub.com/pytest-dev/pytest/issues/7429): Add more information and use cases about skipping doctests. - [#​7780](https://togithub.com/pytest-dev/pytest/issues/7780): Classes which should not be inherited from are now marked `final class` in the API reference. - [#​7872](https://togithub.com/pytest-dev/pytest/issues/7872): `_pytest.config.argparsing.Parser.addini()` accepts explicit `None` and `"string"`. - [#​7878](https://togithub.com/pytest-dev/pytest/issues/7878): In pull request section, ask to commit after editing changelog and authors file. ## Trivial/Internal Changes - [#​7802](https://togithub.com/pytest-dev/pytest/issues/7802): The `attrs` dependency requirement is now >=19.2.0 instead of >=17.4.0. - [#​8014](https://togithub.com/pytest-dev/pytest/issues/8014): .pyc files created by pytest's assertion rewriting now conform to the newer PEP-552 format on Python>=3.7. (These files are internal and only interpreted by pytest itself.) ### [`v6.1.2`](https://togithub.com/pytest-dev/pytest/releases/6.1.2) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.1.1...6.1.2) # pytest 6.1.2 (2020-10-28) ## Bug Fixes - [#​7758](https://togithub.com/pytest-dev/pytest/issues/7758): Fixed an issue where some files in packages are getting lost from `--lf` even though they contain tests that failed. Regressed in pytest 5.4.0. - [#​7911](https://togithub.com/pytest-dev/pytest/issues/7911): Directories created by tmpdir are now considered stale after 3 days without modification (previous value was 3 hours) to avoid deleting directories still in use in long running test suites. ## Improved Documentation - [#​7815](https://togithub.com/pytest-dev/pytest/issues/7815): Improve deprecation warning message for `pytest._fillfuncargs()`. ### [`v6.1.1`](https://togithub.com/pytest-dev/pytest/releases/6.1.1) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.1.0...6.1.1) # pytest 6.1.1 (2020-10-03) ## Bug Fixes - [#​7807](https://togithub.com/pytest-dev/pytest/issues/7807): Fixed regression in pytest 6.1.0 causing incorrect rootdir to be determined in some non-trivial cases where parent directories have config files as well. - [#​7814](https://togithub.com/pytest-dev/pytest/issues/7814): Fixed crash in header reporting when testpaths is used and contains absolute paths (regression in 6.1.0). ### [`v6.1.0`](https://togithub.com/pytest-dev/pytest/releases/6.1.0) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.0.2...6.1.0) # pytest 6.1.0 (2020-09-26) ## Breaking Changes - [#​5585](https://togithub.com/pytest-dev/pytest/issues/5585): As per our policy, the following features which have been deprecated in the 5.X series are now removed: - The `funcargnames` read-only property of `FixtureRequest`, `Metafunc`, and `Function` classes. Use `fixturenames` attribute. - `@pytest.fixture` no longer supports positional arguments, pass all arguments by keyword instead. - Direct construction of `Node` subclasses now raise an error, use `from_parent` instead. - The default value for `junit_family` has changed to `xunit2`. If you require the old format, add `junit_family=xunit1` to your configuration file. - The `TerminalReporter` no longer has a `writer` attribute. Plugin authors may use the public functions of the `TerminalReporter` instead of accessing the `TerminalWriter` object directly. - The `--result-log` option has been removed. Users are recommended to use the [pytest-reportlog](https://togithub.com/pytest-dev/pytest-reportlog) plugin instead. For more information consult [Deprecations and Removals](https://docs.pytest.org/en/stable/deprecations.html) in the docs. ## Deprecations - [#​6981](https://togithub.com/pytest-dev/pytest/issues/6981): The `pytest.collect` module is deprecated: all its names can be imported from `pytest` directly. - [#​7097](https://togithub.com/pytest-dev/pytest/issues/7097): The `pytest._fillfuncargs` function is deprecated. This function was kept for backward compatibility with an older plugin. It's functionality is not meant to be used directly, but if you must replace it, use function.\_request.\_fillfixtures() instead, though note this is not a public API and may break in the future. - [#​7210](https://togithub.com/pytest-dev/pytest/issues/7210): The special `-k '-expr'` syntax to `-k` is deprecated. Use `-k 'not expr'` instead. The special `-k 'expr:'` syntax to `-k` is deprecated. Please open an issue if you use this and want a replacement. - [#​7255](https://togithub.com/pytest-dev/pytest/issues/7255): The pytest_warning_captured <\_pytest.hookspec.pytest_warning_captured> hook is deprecated in favor of pytest_warning_recorded <\_pytest.hookspec.pytest_warning_recorded>, and will be removed in a future version. - [#​7648](https://togithub.com/pytest-dev/pytest/issues/7648): The `gethookproxy()` and `isinitpath()` methods of `FSCollector` and `Package` are deprecated; use `self.session.gethookproxy()` and `self.session.isinitpath()` instead. This should work on all pytest versions. ## Features - [#​7667](https://togithub.com/pytest-dev/pytest/issues/7667): New `--durations-min` command-line flag controls the minimal duration for inclusion in the slowest list of tests shown by `--durations`. Previously this was hard-coded to `0.005s`. ## Improvements - [#​6681](https://togithub.com/pytest-dev/pytest/issues/6681): Internal pytest warnings issued during the early stages of initialization are now properly handled and can filtered through filterwarnings or `--pythonwarnings/-W`. This also fixes a number of long standing issues: [#​2891](https://togithub.com/pytest-dev/pytest/issues/2891), [#​7620](https://togithub.com/pytest-dev/pytest/issues/7620), [#​7426](https://togithub.com/pytest-dev/pytest/issues/7426). - [#​7572](https://togithub.com/pytest-dev/pytest/issues/7572): When a plugin listed in `required_plugins` is missing or an unknown config key is used with `--strict-config`, a simple error message is now shown instead of a stacktrace. - [#​7685](https://togithub.com/pytest-dev/pytest/issues/7685): Added two new attributes rootpath <\_pytest.config.Config.rootpath> and inipath <\_pytest.config.Config.inipath> to Config <\_pytest.config.Config>. These attributes are pathlib.Path versions of the existing rootdir <\_pytest.config.Config.rootdir> and inifile <\_pytest.config.Config.inifile> attributes, and should be preferred over them when possible. - [#​7780](https://togithub.com/pytest-dev/pytest/issues/7780): Public classes which are not designed to be inherited from are now marked [@​final](https://docs.python.org/3/library/typing.html#typing.final). Code which inherits from these classes will trigger a type-checking (e.g. mypy) error, but will still work in runtime. Currently the `final` designation does not appear in the API Reference but hopefully will in the future. ## Bug Fixes - [#​1953](https://togithub.com/pytest-dev/pytest/issues/1953): Fixed error when overwriting a parametrized fixture, while also reusing the super fixture value. ```{.sourceCode .python} ``` ### conftest.py import pytest @​pytest.fixture(params=[1, 2]) def foo(request): return request.param ### test_foo.py import pytest @​pytest.fixture def foo(foo): return foo * 2 ``` - [#​4984](https://togithub.com/pytest-dev/pytest/issues/4984): Fixed an internal error crash with `IndexError: list index out of range` when collecting a module which starts with a decorated function, the decorator raises, and assertion rewriting is enabled. - [#​7591](https://togithub.com/pytest-dev/pytest/issues/7591): pylint shouldn't complain anymore about unimplemented abstract methods when inheriting from File \. - [#​7628](https://togithub.com/pytest-dev/pytest/issues/7628): Fixed test collection when a full path without a drive letter was passed to pytest on Windows (for example `\projects\tests\test.py` instead of `c:\projects\tests\pytest.py`). - [#​7638](https://togithub.com/pytest-dev/pytest/issues/7638): Fix handling of command-line options that appear as paths but trigger an OS-level syntax error on Windows, such as the options used internally by `pytest-xdist`. - [#​7742](https://togithub.com/pytest-dev/pytest/issues/7742): Fixed INTERNALERROR when accessing locals / globals with faulty `exec`. ## Improved Documentation - [#​1477](https://togithub.com/pytest-dev/pytest/issues/1477): Removed faq.rst and its reference in contents.rst. ## Trivial/Internal Changes - [#​7536](https://togithub.com/pytest-dev/pytest/issues/7536): The internal `junitxml` plugin has rewritten to use `xml.etree.ElementTree`. The order of attributes in XML elements might differ. Some unneeded escaping is no longer performed. - [#​7587](https://togithub.com/pytest-dev/pytest/issues/7587): The dependency on the `more-itertools` package has been removed. - [#​7631](https://togithub.com/pytest-dev/pytest/issues/7631): The result type of capfd.readouterr() <\_pytest.capture.CaptureFixture.readouterr> (and similar) is no longer a namedtuple, but should behave like one in all respects. This was done for technical reasons. - [#​7671](https://togithub.com/pytest-dev/pytest/issues/7671): When collecting tests, pytest finds test classes and functions by examining the attributes of python objects (modules, classes and instances). To speed up this process, pytest now ignores builtin attributes (like `__class__`, `__delattr__` and `__new__`) without consulting the python_classes and python_functions configuration options and without passing them to plugins using the pytest_pycollect_makeitem <\_pytest.hookspec.pytest_pycollect_makeitem> hook. ### [`v6.0.2`](https://togithub.com/pytest-dev/pytest/releases/6.0.2) [Compare Source](https://togithub.com/pytest-dev/pytest/compare/6.0.1...6.0.2) # pytest 6.0.2 (2020-09-04) ## Bug Fixes - [#​7148](https://togithub.com/pytest-dev/pytest/issues/7148): Fixed `--log-cli` potentially causing unrelated `print` output to be swallowed. - [#​7672](https://togithub.com/pytest-dev/pytest/issues/7672): Fixed log-capturing level restored incorrectly if `caplog.set_level` is called more than once. - [#​7686](https://togithub.com/pytest-dev/pytest/issues/7686): Fixed NotSetType.token being used as the parameter ID when the parametrization list is empty. Regressed in pytest 6.0.0. - [#​7707](https://togithub.com/pytest-dev/pytest/issues/7707): Fix internal error when handling some exceptions that contain multiple lines or the style uses multiple lines (`--tb=line` for example).
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻️ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/python-talent). --- samples/snippets/requirements-test.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 573c2eb36db6db0858e798b5121a4ad25b549dee Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 17 Jun 2021 10:52:22 +0000 Subject: [PATCH 19/26] chore: new owl bot post processor docker image (#108) Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:58c7342b0bccf85028100adaa3d856cb4a871c22ca9c01960d996e66c40548ce --- .github/.OwlBot.lock.yaml | 2 +- docs/conf.py | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 4ef44149..ea06d395 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 \ No newline at end of file + digest: sha256:58c7342b0bccf85028100adaa3d856cb4a871c22ca9c01960d996e66c40548ce diff --git a/docs/conf.py b/docs/conf.py index 013a849a..1b57beeb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -80,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 @@ -281,7 +281,7 @@ ( master_doc, "google-cloud-talent.tex", - u"google-cloud-talent Documentation", + "google-cloud-talent Documentation", author, "manual", ) @@ -316,7 +316,7 @@ ( master_doc, "google-cloud-talent", - u"google-cloud-talent Documentation", + "google-cloud-talent Documentation", [author], 1, ) @@ -335,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", From fe89307a7288e02aaeadb4d582a4b0bd7aa1d221 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 19 Jun 2021 01:36:20 +0000 Subject: [PATCH 20/26] docs: omit mention of Python 2.7 in 'CONTRIBUTING.rst' (#1127) (#109) Closes #1126 Source-Link: https://github.com/googleapis/synthtool/commit/b91f129527853d5b756146a0b5044481fb4e09a8 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:b6169fc6a5207b11800a7c002d0c5c2bc6d82697185ca12e666f44031468cfcd --- .github/.OwlBot.lock.yaml | 2 +- CONTRIBUTING.rst | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index ea06d395..cc49c6a3 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:58c7342b0bccf85028100adaa3d856cb4a871c22ca9c01960d996e66c40548ce + digest: sha256:b6169fc6a5207b11800a7c002d0c5c2bc6d82697185ca12e666f44031468cfcd diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 1c900d9d..631541d1 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -69,7 +69,6 @@ We use `nox `__ to instrument our tests. - To test your changes, run unit tests with ``nox``:: - $ nox -s unit-2.7 $ nox -s unit-3.8 $ ... @@ -144,7 +143,6 @@ Running System Tests # Run all system tests $ nox -s system-3.8 - $ nox -s system-2.7 # Run a single system test $ nox -s system-3.8 -- -k @@ -152,9 +150,8 @@ Running System Tests .. note:: - System tests are only configured to run under Python 2.7 and - Python 3.8. 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 From 4c734ec2b6e5b2114ae7a1c55077295471d102b2 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sun, 20 Jun 2021 01:00:21 +0000 Subject: [PATCH 21/26] chore: update precommit hook pre-commit/pre-commit-hooks to v4 (#1083) (#110) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [pre-commit/pre-commit-hooks](https://togithub.com/pre-commit/pre-commit-hooks) | repository | major | `v3.4.0` -> `v4.0.1` | --- ### Release Notes
pre-commit/pre-commit-hooks ### [`v4.0.1`](https://togithub.com/pre-commit/pre-commit-hooks/releases/v4.0.1) [Compare Source](https://togithub.com/pre-commit/pre-commit-hooks/compare/v4.0.0...v4.0.1) ##### Fixes - `check-shebang-scripts-are-executable` fix entry point. - [#​602](https://togithub.com/pre-commit/pre-commit-hooks/issues/602) issue by [@​Person-93](https://togithub.com/Person-93). - [#​603](https://togithub.com/pre-commit/pre-commit-hooks/issues/603) PR by [@​scop](https://togithub.com/scop). ### [`v4.0.0`](https://togithub.com/pre-commit/pre-commit-hooks/releases/v4.0.0) [Compare Source](https://togithub.com/pre-commit/pre-commit-hooks/compare/v3.4.0...v4.0.0) ##### Features - `check-json`: report duplicate keys. - [#​558](https://togithub.com/pre-commit/pre-commit-hooks/issues/558) PR by [@​AdityaKhursale](https://togithub.com/AdityaKhursale). - [#​554](https://togithub.com/pre-commit/pre-commit-hooks/issues/554) issue by [@​adamchainz](https://togithub.com/adamchainz). - `no-commit-to-branch`: add `main` to default blocked branches. - [#​565](https://togithub.com/pre-commit/pre-commit-hooks/issues/565) PR by [@​ndevenish](https://togithub.com/ndevenish). - `check-case-conflict`: check conflicts in directory names as well. - [#​575](https://togithub.com/pre-commit/pre-commit-hooks/issues/575) PR by [@​slsyy](https://togithub.com/slsyy). - [#​70](https://togithub.com/pre-commit/pre-commit-hooks/issues/70) issue by [@​andyjack](https://togithub.com/andyjack). - `check-vcs-permalinks`: forbid other branch names. - [#​582](https://togithub.com/pre-commit/pre-commit-hooks/issues/582) PR by [@​jack1142](https://togithub.com/jack1142). - [#​581](https://togithub.com/pre-commit/pre-commit-hooks/issues/581) issue by [@​jack1142](https://togithub.com/jack1142). - `check-shebang-scripts-are-executable`: new hook which ensures shebang'd scripts are executable. - [#​545](https://togithub.com/pre-commit/pre-commit-hooks/issues/545) PR by [@​scop](https://togithub.com/scop). ##### Fixes - `check-executables-have-shebangs`: Short circuit shebang lookup on windows. - [#​544](https://togithub.com/pre-commit/pre-commit-hooks/issues/544) PR by [@​scop](https://togithub.com/scop). - `requirements-txt-fixer`: Fix comments which have indentation - [#​549](https://togithub.com/pre-commit/pre-commit-hooks/issues/549) PR by [@​greshilov](https://togithub.com/greshilov). - [#​548](https://togithub.com/pre-commit/pre-commit-hooks/issues/548) issue by [@​greshilov](https://togithub.com/greshilov). - `pretty-format-json`: write to stdout using UTF-8 encoding. - [#​571](https://togithub.com/pre-commit/pre-commit-hooks/issues/571) PR by [@​jack1142](https://togithub.com/jack1142). - [#​570](https://togithub.com/pre-commit/pre-commit-hooks/issues/570) issue by [@​jack1142](https://togithub.com/jack1142). - Use more inclusive language. - [#​599](https://togithub.com/pre-commit/pre-commit-hooks/issues/599) PR by [@​asottile](https://togithub.com/asottile). ##### Breaking changes - Remove deprecated hooks: `flake8`, `pyflakes`, `autopep8-wrapper`. - [#​597](https://togithub.com/pre-commit/pre-commit-hooks/issues/597) PR by [@​asottile](https://togithub.com/asottile).
--- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻️ **Rebasing**: Renovate will not automatically rebase this PR, because other commits have been found. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, check this box. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/synthtool). Source-Link: https://github.com/googleapis/synthtool/commit/333fd90856f1454380514bc59fc0936cdaf1c202 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:b8c131c558606d3cea6e18f8e87befbd448c1482319b0db3c5d5388fa6ea72e3 --- .github/.OwlBot.lock.yaml | 2 +- .pre-commit-config.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index cc49c6a3..9602d540 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:b6169fc6a5207b11800a7c002d0c5c2bc6d82697185ca12e666f44031468cfcd + digest: sha256:b8c131c558606d3cea6e18f8e87befbd448c1482319b0db3c5d5388fa6ea72e3 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4f00c7cf..62eb5a77 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ # 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 From bd8e651ca54e7fb7d7342de0933253babf5c517a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 21 Jun 2021 15:55:56 -0600 Subject: [PATCH 22/26] chore: add kokoro 3.9 config templates (#1128) (#111) fixes #907 Source-Link: https://github.com/googleapis/synthtool/commit/b0eb8a8b30b46a3c98d23c23107acb748c6601a1 Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:df50e8d462f86d6bcb42f27ecad55bb12c404f1c65de9c6fe4c4d25120080bd6 Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/samples/python3.9/common.cfg | 40 +++++++++++++++++++++ .kokoro/samples/python3.9/continuous.cfg | 6 ++++ .kokoro/samples/python3.9/periodic-head.cfg | 11 ++++++ .kokoro/samples/python3.9/periodic.cfg | 6 ++++ .kokoro/samples/python3.9/presubmit.cfg | 6 ++++ 6 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 .kokoro/samples/python3.9/common.cfg create mode 100644 .kokoro/samples/python3.9/continuous.cfg create mode 100644 .kokoro/samples/python3.9/periodic-head.cfg create mode 100644 .kokoro/samples/python3.9/periodic.cfg create mode 100644 .kokoro/samples/python3.9/presubmit.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 9602d540..0954585f 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:b8c131c558606d3cea6e18f8e87befbd448c1482319b0db3c5d5388fa6ea72e3 + digest: sha256:df50e8d462f86d6bcb42f27ecad55bb12c404f1c65de9c6fe4c4d25120080bd6 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 From 01c8095182503fa8d7ca593f4701f87fe00621ff Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 23 Jun 2021 20:24:33 +0000 Subject: [PATCH 23/26] feat: add always_use_jwt_access (#112) ... chore: update gapic-generator-ruby to the latest commit chore: release gapic-generator-typescript 1.5.0 Committer: @miraleung PiperOrigin-RevId: 380641501 Source-Link: https://github.com/googleapis/googleapis/commit/076f7e9f0b258bdb54338895d7251b202e8f0de3 Source-Link: https://github.com/googleapis/googleapis-gen/commit/27e4c88b4048e5f56508d4e1aa417d60a3380892 --- .coveragerc | 1 - .../company_service/transports/base.py | 40 +++---- .../company_service/transports/grpc.py | 7 +- .../transports/grpc_asyncio.py | 7 +- .../services/completion/transports/base.py | 40 +++---- .../services/completion/transports/grpc.py | 7 +- .../completion/transports/grpc_asyncio.py | 7 +- .../services/event_service/transports/base.py | 40 +++---- .../services/event_service/transports/grpc.py | 7 +- .../event_service/transports/grpc_asyncio.py | 7 +- .../services/job_service/transports/base.py | 40 +++---- .../services/job_service/transports/grpc.py | 7 +- .../job_service/transports/grpc_asyncio.py | 7 +- .../tenant_service/transports/base.py | 40 +++---- .../tenant_service/transports/grpc.py | 7 +- .../tenant_service/transports/grpc_asyncio.py | 7 +- .../application_service/transports/base.py | 40 +++---- .../application_service/transports/grpc.py | 7 +- .../transports/grpc_asyncio.py | 7 +- .../company_service/transports/base.py | 40 +++---- .../company_service/transports/grpc.py | 7 +- .../transports/grpc_asyncio.py | 7 +- .../services/completion/transports/base.py | 40 +++---- .../services/completion/transports/grpc.py | 7 +- .../completion/transports/grpc_asyncio.py | 7 +- .../services/event_service/transports/base.py | 40 +++---- .../services/event_service/transports/grpc.py | 7 +- .../event_service/transports/grpc_asyncio.py | 7 +- .../services/job_service/transports/base.py | 40 +++---- .../services/job_service/transports/grpc.py | 7 +- .../job_service/transports/grpc_asyncio.py | 7 +- .../profile_service/transports/base.py | 40 +++---- .../profile_service/transports/grpc.py | 7 +- .../transports/grpc_asyncio.py | 7 +- .../tenant_service/transports/base.py | 40 +++---- .../tenant_service/transports/grpc.py | 7 +- .../tenant_service/transports/grpc_asyncio.py | 7 +- setup.py | 2 +- testing/constraints-3.6.txt | 2 +- .../gapic/talent_v4/test_company_service.py | 107 +++--------------- tests/unit/gapic/talent_v4/test_completion.py | 101 +++-------------- .../gapic/talent_v4/test_event_service.py | 105 +++-------------- .../unit/gapic/talent_v4/test_job_service.py | 105 +++-------------- .../gapic/talent_v4/test_tenant_service.py | 107 +++--------------- .../test_application_service.py | 107 +++--------------- .../talent_v4beta1/test_company_service.py | 107 +++--------------- .../gapic/talent_v4beta1/test_completion.py | 103 +++-------------- .../talent_v4beta1/test_event_service.py | 105 +++-------------- .../gapic/talent_v4beta1/test_job_service.py | 105 +++-------------- .../talent_v4beta1/test_profile_service.py | 107 +++--------------- .../talent_v4beta1/test_tenant_service.py | 107 +++--------------- 51 files changed, 434 insertions(+), 1485 deletions(-) diff --git a/.coveragerc b/.coveragerc index 8a9e352c..4ad22152 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,7 +2,6 @@ branch = True [report] -fail_under = 100 show_missing = True omit = google/cloud/talent/__init__.py 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 8bff9984..64fe527c 100644 --- a/google/cloud/talent_v4/services/company_service/transports/base.py +++ b/google/cloud/talent_v4/services/company_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -46,8 +47,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class CompanyServiceTransport(abc.ABC): """Abstract transport class for CompanyService.""" @@ -68,6 +67,7 @@ def __init__( 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. @@ -91,6 +91,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -119,13 +121,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -146,27 +155,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 b8b64af5..94ffded5 100644 --- a/google/cloud/talent_v4/services/company_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/company_service/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -208,14 +209,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 838acfa0..14ac7556 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 @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/google/cloud/talent_v4/services/completion/transports/base.py b/google/cloud/talent_v4/services/completion/transports/base.py index 799b28c6..b26b2c48 100644 --- a/google/cloud/talent_v4/services/completion/transports/base.py +++ b/google/cloud/talent_v4/services/completion/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -43,8 +44,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class CompletionTransport(abc.ABC): """Abstract transport class for Completion.""" @@ -65,6 +64,7 @@ def __init__( 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. @@ -88,6 +88,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -116,13 +118,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -143,27 +152,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/talent_v4/services/completion/transports/grpc.py b/google/cloud/talent_v4/services/completion/transports/grpc.py index 371fc914..5d2ce49e 100644 --- a/google/cloud/talent_v4/services/completion/transports/grpc.py +++ b/google/cloud/talent_v4/services/completion/transports/grpc.py @@ -149,6 +149,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -204,14 +205,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + 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 8c22b5ec..bf8d05a1 100644 --- a/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py +++ b/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py @@ -78,14 +78,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -195,6 +195,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 064b5bf4..e9bed039 100644 --- a/google/cloud/talent_v4/services/event_service/transports/base.py +++ b/google/cloud/talent_v4/services/event_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -44,8 +45,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class EventServiceTransport(abc.ABC): """Abstract transport class for EventService.""" @@ -66,6 +65,7 @@ def __init__( 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. @@ -89,6 +89,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -117,13 +119,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -144,27 +153,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 73878a96..730fdaeb 100644 --- a/google/cloud/talent_v4/services/event_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/event_service/transports/grpc.py @@ -150,6 +150,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -205,14 +206,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + 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 c1e89c3a..5cd24a59 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 @@ -79,14 +79,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -196,6 +196,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 452fb3f5..03cd109f 100644 --- a/google/cloud/talent_v4/services/job_service/transports/base.py +++ b/google/cloud/talent_v4/services/job_service/transports/base.py @@ -25,6 +25,7 @@ from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # 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 @@ -48,8 +49,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class JobServiceTransport(abc.ABC): """Abstract transport class for JobService.""" @@ -70,6 +69,7 @@ def __init__( 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. @@ -93,6 +93,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -121,13 +123,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -148,27 +157,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 3acde84a..0f57d199 100644 --- a/google/cloud/talent_v4/services/job_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/job_service/transports/grpc.py @@ -156,6 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -211,14 +212,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 6f75a23b..12638fff 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 @@ -84,14 +84,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -202,6 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 074d4307..8c5d88d7 100644 --- a/google/cloud/talent_v4/services/tenant_service/transports/base.py +++ b/google/cloud/talent_v4/services/tenant_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -46,8 +47,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TenantServiceTransport(abc.ABC): """Abstract transport class for TenantService.""" @@ -68,6 +67,7 @@ def __init__( 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. @@ -91,6 +91,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -119,13 +121,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -146,27 +155,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 75eaec9d..c535708a 100644 --- a/google/cloud/talent_v4/services/tenant_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/tenant_service/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -208,14 +209,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 e58a8d87..820e3673 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 @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 6e8230fe..54295352 100644 --- a/google/cloud/talent_v4beta1/services/application_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/application_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -46,8 +47,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ApplicationServiceTransport(abc.ABC): """Abstract transport class for ApplicationService.""" @@ -68,6 +67,7 @@ def __init__( 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. @@ -91,6 +91,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -119,13 +121,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -146,27 +155,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 e2eb0eed..f32eebdf 100644 --- a/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -208,14 +209,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 ee0502d9..ce7d8e13 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 @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 32ffd8fe..f49ddcdf 100644 --- a/google/cloud/talent_v4beta1/services/company_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/company_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -46,8 +47,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class CompanyServiceTransport(abc.ABC): """Abstract transport class for CompanyService.""" @@ -68,6 +67,7 @@ def __init__( 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. @@ -91,6 +91,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -119,13 +121,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -146,27 +155,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 88044b80..5c9a0b89 100644 --- a/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -208,14 +209,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 91bdd6fa..e615f8e7 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 @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/google/cloud/talent_v4beta1/services/completion/transports/base.py b/google/cloud/talent_v4beta1/services/completion/transports/base.py index 1f49c232..cd4fcba0 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/base.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -43,8 +44,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class CompletionTransport(abc.ABC): """Abstract transport class for Completion.""" @@ -65,6 +64,7 @@ def __init__( 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. @@ -88,6 +88,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -116,13 +118,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -143,27 +152,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py index 1886e170..5f84b027 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py @@ -149,6 +149,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -204,14 +205,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + 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 7df7ee5a..c0a6dd7d 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py @@ -78,14 +78,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -195,6 +195,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 edf4dd0f..069cada5 100644 --- a/google/cloud/talent_v4beta1/services/event_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/event_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -44,8 +45,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class EventServiceTransport(abc.ABC): """Abstract transport class for EventService.""" @@ -66,6 +65,7 @@ def __init__( 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. @@ -89,6 +89,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -117,13 +119,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -144,27 +153,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 c0669a2b..467ca194 100644 --- a/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py @@ -150,6 +150,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -205,14 +206,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + 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 347587fc..26dfdd46 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 @@ -79,14 +79,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -196,6 +196,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 12c5fac1..fb769dd4 100644 --- a/google/cloud/talent_v4beta1/services/job_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/job_service/transports/base.py @@ -25,6 +25,7 @@ from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # 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 @@ -48,8 +49,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class JobServiceTransport(abc.ABC): """Abstract transport class for JobService.""" @@ -70,6 +69,7 @@ def __init__( 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. @@ -93,6 +93,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -121,13 +123,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -148,27 +157,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 85ecd085..6371a285 100644 --- a/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py @@ -156,6 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -211,14 +212,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 5d7613c6..d99af105 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 @@ -84,14 +84,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -202,6 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 3320cbfd..8a380697 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/profile_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -46,8 +47,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class ProfileServiceTransport(abc.ABC): """Abstract transport class for ProfileService.""" @@ -68,6 +67,7 @@ def __init__( 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. @@ -91,6 +91,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -119,13 +121,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -146,27 +155,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 fdd944e3..ac20eda5 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -208,14 +209,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 e5fea4ab..05bf8cc2 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 @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: 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 d61181b5..77c48040 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # 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 @@ -46,8 +47,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class TenantServiceTransport(abc.ABC): """Abstract transport class for TenantService.""" @@ -68,6 +67,7 @@ def __init__( 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. @@ -91,6 +91,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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -119,13 +121,20 @@ def __init__( **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 - # TODO(busunkim): These two class methods are in the base transport + # 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-api-core - # and google-auth are increased. + # 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 @@ -146,27 +155,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { 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 e80b73ea..ee8ee728 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py @@ -153,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: @@ -208,14 +209,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) 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 1203c8fe..f6e20bc8 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 @@ -82,14 +82,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -199,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=True, ) if not self._grpc_channel: diff --git a/setup.py b/setup.py index 290ff778..843ac285 100644 --- a/setup.py +++ b/setup.py @@ -29,7 +29,7 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 4 - Beta" dependencies = [ - "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "google-api-core[grpc] >= 1.26.0, <2.0.0dev", "proto-plus >= 1.15.0", "packaging >= 14.3", ] diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 29486a27..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.2 +google-api-core==1.26.0 proto-plus==1.15.0 packaging==14.3 diff --git a/tests/unit/gapic/talent_v4/test_company_service.py b/tests/unit/gapic/talent_v4/test_company_service.py index c77ebb7e..de0371b1 100644 --- a/tests/unit/gapic/talent_v4/test_company_service.py +++ b/tests/unit/gapic/talent_v4/test_company_service.py @@ -35,9 +35,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4.services.company_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -52,8 +49,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -64,16 +62,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -136,6 +124,18 @@ def test_company_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize( "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,] ) @@ -2038,7 +2038,6 @@ def test_company_service_transport_auth_adc_old_google_auth(transport_class): (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -2070,82 +2069,6 @@ def test_company_service_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompanyServiceGrpcTransport, grpc_helpers), - (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_company_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompanyServiceGrpcTransport, grpc_helpers), - (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_company_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ diff --git a/tests/unit/gapic/talent_v4/test_completion.py b/tests/unit/gapic/talent_v4/test_completion.py index 76aa5c8f..3e53b9b1 100644 --- a/tests/unit/gapic/talent_v4/test_completion.py +++ b/tests/unit/gapic/talent_v4/test_completion.py @@ -34,7 +34,6 @@ 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 _API_CORE_VERSION from google.cloud.talent_v4.services.completion.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -44,8 +43,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -56,16 +56,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -123,6 +113,16 @@ def test_completion_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,]) def test_completion_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -823,7 +823,6 @@ def test_completion_transport_auth_adc_old_google_auth(transport_class): (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 def test_completion_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -855,80 +854,6 @@ def test_completion_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionGrpcTransport, grpc_helpers), - (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_completion_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionGrpcTransport, grpc_helpers), - (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_completion_transport_create_channel_user_scopes(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", - scopes=["1", "2"], - 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], diff --git a/tests/unit/gapic/talent_v4/test_event_service.py b/tests/unit/gapic/talent_v4/test_event_service.py index c8b25148..31481d92 100644 --- a/tests/unit/gapic/talent_v4/test_event_service.py +++ b/tests/unit/gapic/talent_v4/test_event_service.py @@ -34,9 +34,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4.services.event_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -126,6 +114,16 @@ def test_event_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,]) def test_event_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -935,7 +933,6 @@ def test_event_service_transport_auth_adc_old_google_auth(transport_class): (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -967,82 +964,6 @@ def test_event_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EventServiceGrpcTransport, grpc_helpers), - (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_event_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EventServiceGrpcTransport, grpc_helpers), - (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_event_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], diff --git a/tests/unit/gapic/talent_v4/test_job_service.py b/tests/unit/gapic/talent_v4/test_job_service.py index dee2b9d5..8a65b4c1 100644 --- a/tests/unit/gapic/talent_v4/test_job_service.py +++ b/tests/unit/gapic/talent_v4/test_job_service.py @@ -38,9 +38,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4.services.job_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -63,8 +60,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -75,16 +73,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -142,6 +130,16 @@ def test_job_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,]) def test_job_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -2989,7 +2987,6 @@ def test_job_service_transport_auth_adc_old_google_auth(transport_class): (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -3021,82 +3018,6 @@ def test_job_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.JobServiceGrpcTransport, grpc_helpers), - (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_job_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.JobServiceGrpcTransport, grpc_helpers), - (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_job_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], diff --git a/tests/unit/gapic/talent_v4/test_tenant_service.py b/tests/unit/gapic/talent_v4/test_tenant_service.py index 5704524f..e6d070d5 100644 --- a/tests/unit/gapic/talent_v4/test_tenant_service.py +++ b/tests/unit/gapic/talent_v4/test_tenant_service.py @@ -35,9 +35,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4.services.tenant_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -133,6 +121,18 @@ def test_tenant_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize( "client_class", [TenantServiceClient, TenantServiceAsyncClient,] ) @@ -1873,7 +1873,6 @@ def test_tenant_service_transport_auth_adc_old_google_auth(transport_class): (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -1905,82 +1904,6 @@ def test_tenant_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TenantServiceGrpcTransport, grpc_helpers), - (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_tenant_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TenantServiceGrpcTransport, grpc_helpers), - (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_tenant_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ diff --git a/tests/unit/gapic/talent_v4beta1/test_application_service.py b/tests/unit/gapic/talent_v4beta1/test_application_service.py index 9fb331b0..529b93e7 100644 --- a/tests/unit/gapic/talent_v4beta1/test_application_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_application_service.py @@ -39,9 +39,6 @@ ) 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4beta1.services.application_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -57,8 +54,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -69,16 +67,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -142,6 +130,18 @@ def test_application_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize( "client_class", [ApplicationServiceClient, ApplicationServiceAsyncClient,] ) @@ -2143,7 +2143,6 @@ def test_application_service_transport_auth_adc_old_google_auth(transport_class) (transports.ApplicationServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -2175,82 +2174,6 @@ def test_application_service_transport_create_channel(transport_class, grpc_help ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ApplicationServiceGrpcTransport, grpc_helpers), - (transports.ApplicationServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_application_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ApplicationServiceGrpcTransport, grpc_helpers), - (transports.ApplicationServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_application_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ diff --git a/tests/unit/gapic/talent_v4beta1/test_company_service.py b/tests/unit/gapic/talent_v4beta1/test_company_service.py index 0fbb0bbe..cbfa90a5 100644 --- a/tests/unit/gapic/talent_v4beta1/test_company_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_company_service.py @@ -37,9 +37,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4beta1.services.company_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -54,8 +51,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -66,16 +64,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -138,6 +126,18 @@ def test_company_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize( "client_class", [CompanyServiceClient, CompanyServiceAsyncClient,] ) @@ -2032,7 +2032,6 @@ def test_company_service_transport_auth_adc_old_google_auth(transport_class): (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -2064,82 +2063,6 @@ def test_company_service_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompanyServiceGrpcTransport, grpc_helpers), - (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_company_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompanyServiceGrpcTransport, grpc_helpers), - (transports.CompanyServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_company_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ diff --git a/tests/unit/gapic/talent_v4beta1/test_completion.py b/tests/unit/gapic/talent_v4beta1/test_completion.py index 1c2b8fb1..e697ed57 100644 --- a/tests/unit/gapic/talent_v4beta1/test_completion.py +++ b/tests/unit/gapic/talent_v4beta1/test_completion.py @@ -34,9 +34,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4beta1.services.completion.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -46,8 +43,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -58,16 +56,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -125,6 +113,16 @@ def test_completion_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize("client_class", [CompletionClient, CompletionAsyncClient,]) def test_completion_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -825,7 +823,6 @@ def test_completion_transport_auth_adc_old_google_auth(transport_class): (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 def test_completion_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. @@ -857,80 +854,6 @@ def test_completion_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionGrpcTransport, grpc_helpers), - (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_completion_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.CompletionGrpcTransport, grpc_helpers), - (transports.CompletionGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_completion_transport_create_channel_user_scopes(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", - scopes=["1", "2"], - 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], diff --git a/tests/unit/gapic/talent_v4beta1/test_event_service.py b/tests/unit/gapic/talent_v4beta1/test_event_service.py index 50a09ce8..b24847ed 100644 --- a/tests/unit/gapic/talent_v4beta1/test_event_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_event_service.py @@ -34,9 +34,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4beta1.services.event_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -126,6 +114,16 @@ def test_event_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize("client_class", [EventServiceClient, EventServiceAsyncClient,]) def test_event_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -935,7 +933,6 @@ def test_event_service_transport_auth_adc_old_google_auth(transport_class): (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -967,82 +964,6 @@ def test_event_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EventServiceGrpcTransport, grpc_helpers), - (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_event_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EventServiceGrpcTransport, grpc_helpers), - (transports.EventServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_event_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], diff --git a/tests/unit/gapic/talent_v4beta1/test_job_service.py b/tests/unit/gapic/talent_v4beta1/test_job_service.py index bb88f711..dc03b773 100644 --- a/tests/unit/gapic/talent_v4beta1/test_job_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_job_service.py @@ -38,9 +38,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4beta1.services.job_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -63,8 +60,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -75,16 +73,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -142,6 +130,16 @@ def test_job_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize("client_class", [JobServiceClient, JobServiceAsyncClient,]) def test_job_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -3301,7 +3299,6 @@ def test_job_service_transport_auth_adc_old_google_auth(transport_class): (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -3333,82 +3330,6 @@ def test_job_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.JobServiceGrpcTransport, grpc_helpers), - (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_job_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.JobServiceGrpcTransport, grpc_helpers), - (transports.JobServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_job_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], diff --git a/tests/unit/gapic/talent_v4beta1/test_profile_service.py b/tests/unit/gapic/talent_v4beta1/test_profile_service.py index 29edbff5..e0c302cf 100644 --- a/tests/unit/gapic/talent_v4beta1/test_profile_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_profile_service.py @@ -37,9 +37,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4beta1.services.profile_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -60,8 +57,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -72,16 +70,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -144,6 +132,18 @@ def test_profile_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize( "client_class", [ProfileServiceClient, ProfileServiceAsyncClient,] ) @@ -2287,7 +2287,6 @@ def test_profile_service_transport_auth_adc_old_google_auth(transport_class): (transports.ProfileServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -2319,82 +2318,6 @@ def test_profile_service_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ProfileServiceGrpcTransport, grpc_helpers), - (transports.ProfileServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_profile_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.ProfileServiceGrpcTransport, grpc_helpers), - (transports.ProfileServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_profile_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ diff --git a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py index f5dc15fc..7d9650ec 100644 --- a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py @@ -35,9 +35,6 @@ 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 ( - _API_CORE_VERSION, -) from google.cloud.talent_v4beta1.services.tenant_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -49,8 +46,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# 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"), @@ -61,16 +59,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -133,6 +121,18 @@ def test_tenant_service_client_from_service_account_info(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_called_with(True) + + @pytest.mark.parametrize( "client_class", [TenantServiceClient, TenantServiceAsyncClient,] ) @@ -1925,7 +1925,6 @@ def test_tenant_service_transport_auth_adc_old_google_auth(transport_class): (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -1957,82 +1956,6 @@ def test_tenant_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TenantServiceGrpcTransport, grpc_helpers), - (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_tenant_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "jobs.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/jobs", - ), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.TenantServiceGrpcTransport, grpc_helpers), - (transports.TenantServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_tenant_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - @pytest.mark.parametrize( "transport_class", [ From 77d7f9ab1b726198007e3df148f88f261df544e6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 26 Jun 2021 12:20:21 +0000 Subject: [PATCH 24/26] chore(python): simplify nox steps in CONTRIBUTING.rst (#113) Source-Link: https://github.com/googleapis/synthtool/commit/26558bae8976a985d73c2d98c31d8612273f907d Post-Processor: gcr.io/repo-automation-bots/owlbot-python:latest@sha256:99d90d097e4a4710cc8658ee0b5b963f4426d0e424819787c3ac1405c9a26719 --- .github/.OwlBot.lock.yaml | 2 +- CONTRIBUTING.rst | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0954585f..e2b39f94 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-python:latest - digest: sha256:df50e8d462f86d6bcb42f27ecad55bb12c404f1c65de9c6fe4c4d25120080bd6 + digest: sha256:99d90d097e4a4710cc8658ee0b5b963f4426d0e424819787c3ac1405c9a26719 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 631541d1..124cba6b 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -68,14 +68,12 @@ Using ``nox`` We use `nox `__ to instrument our tests. - To test your changes, run unit tests with ``nox``:: + $ nox -s unit - $ nox -s unit-3.8 - $ ... +- To run a single unit test:: -- Args to pytest can be passed through the nox command separated by a `--`. For - example, to run a single test:: + $ nox -s unit-3.9 -- -k - $ nox -s unit-3.8 -- -k .. note:: @@ -142,7 +140,7 @@ Running System Tests - To run system tests, you can execute:: # Run all system tests - $ nox -s system-3.8 + $ nox -s system # Run a single system test $ nox -s system-3.8 -- -k @@ -215,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`_ From a422ac00d270bef6f66d6d29b674505c3a152e33 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 30 Jun 2021 18:22:24 +0000 Subject: [PATCH 25/26] fix: disable always_use_jwt_access (#115) fix: disable always_use_jwt_access Committer: @busunkim96 PiperOrigin-RevId: 382142900 Source-Link: https://github.com/googleapis/googleapis/commit/513440fda515f3c799c22a30e3906dcda325004e Source-Link: https://github.com/googleapis/googleapis-gen/commit/7b1e2c31233f79a704ec21ca410bf661d6bc68d0 --- .../company_service/transports/base.py | 2 +- .../company_service/transports/grpc.py | 5 ++- .../transports/grpc_asyncio.py | 5 ++- .../services/completion/transports/base.py | 2 +- .../services/completion/transports/grpc.py | 5 ++- .../completion/transports/grpc_asyncio.py | 5 ++- .../services/event_service/transports/base.py | 2 +- .../services/event_service/transports/grpc.py | 5 ++- .../event_service/transports/grpc_asyncio.py | 5 ++- .../services/job_service/transports/base.py | 2 +- .../services/job_service/transports/grpc.py | 5 ++- .../job_service/transports/grpc_asyncio.py | 5 ++- .../tenant_service/transports/base.py | 2 +- .../tenant_service/transports/grpc.py | 5 ++- .../tenant_service/transports/grpc_asyncio.py | 5 ++- .../application_service/transports/base.py | 2 +- .../application_service/transports/grpc.py | 5 ++- .../transports/grpc_asyncio.py | 5 ++- .../company_service/transports/base.py | 2 +- .../company_service/transports/grpc.py | 5 ++- .../transports/grpc_asyncio.py | 5 ++- .../services/completion/transports/base.py | 2 +- .../services/completion/transports/grpc.py | 5 ++- .../completion/transports/grpc_asyncio.py | 5 ++- .../services/event_service/transports/base.py | 2 +- .../services/event_service/transports/grpc.py | 5 ++- .../event_service/transports/grpc_asyncio.py | 5 ++- .../services/job_service/transports/base.py | 2 +- .../services/job_service/transports/grpc.py | 5 ++- .../job_service/transports/grpc_asyncio.py | 5 ++- .../profile_service/transports/base.py | 2 +- .../profile_service/transports/grpc.py | 5 ++- .../transports/grpc_asyncio.py | 5 ++- .../tenant_service/transports/base.py | 2 +- .../tenant_service/transports/grpc.py | 5 ++- .../tenant_service/transports/grpc_asyncio.py | 5 ++- .../gapic/talent_v4/test_company_service.py | 35 ++++++++++++------- tests/unit/gapic/talent_v4/test_completion.py | 35 ++++++++++++------- .../gapic/talent_v4/test_event_service.py | 35 ++++++++++++------- .../unit/gapic/talent_v4/test_job_service.py | 35 ++++++++++++------- .../gapic/talent_v4/test_tenant_service.py | 35 ++++++++++++------- .../test_application_service.py | 35 ++++++++++++------- .../talent_v4beta1/test_company_service.py | 35 ++++++++++++------- .../gapic/talent_v4beta1/test_completion.py | 35 ++++++++++++------- .../talent_v4beta1/test_event_service.py | 35 ++++++++++++------- .../gapic/talent_v4beta1/test_job_service.py | 35 ++++++++++++------- .../talent_v4beta1/test_profile_service.py | 35 ++++++++++++------- .../talent_v4beta1/test_tenant_service.py | 35 ++++++++++++------- 48 files changed, 372 insertions(+), 192 deletions(-) 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 64fe527c..a4680262 100644 --- a/google/cloud/talent_v4/services/company_service/transports/base.py +++ b/google/cloud/talent_v4/services/company_service/transports/base.py @@ -102,7 +102,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 94ffded5..aefcd800 100644 --- a/google/cloud/talent_v4/services/company_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/company_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 14ac7556..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 @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/talent_v4/services/completion/transports/base.py b/google/cloud/talent_v4/services/completion/transports/base.py index b26b2c48..95edf7a4 100644 --- a/google/cloud/talent_v4/services/completion/transports/base.py +++ b/google/cloud/talent_v4/services/completion/transports/base.py @@ -99,7 +99,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/talent_v4/services/completion/transports/grpc.py b/google/cloud/talent_v4/services/completion/transports/grpc.py index 5d2ce49e..3b272950 100644 --- a/google/cloud/talent_v4/services/completion/transports/grpc.py +++ b/google/cloud/talent_v4/services/completion/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -97,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 @@ -149,7 +152,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 bf8d05a1..b4c6bc68 100644 --- a/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py +++ b/google/cloud/talent_v4/services/completion/transports/grpc_asyncio.py @@ -103,6 +103,7 @@ def __init__( 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. @@ -144,6 +145,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 @@ -195,7 +198,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 e9bed039..7400fc68 100644 --- a/google/cloud/talent_v4/services/event_service/transports/base.py +++ b/google/cloud/talent_v4/services/event_service/transports/base.py @@ -100,7 +100,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 730fdaeb..3a577771 100644 --- a/google/cloud/talent_v4/services/event_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/event_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( 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. @@ -98,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 @@ -150,7 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 5cd24a59..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 @@ -104,6 +104,7 @@ def __init__( 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. @@ -145,6 +146,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 @@ -196,7 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 03cd109f..6e4ab3c0 100644 --- a/google/cloud/talent_v4/services/job_service/transports/base.py +++ b/google/cloud/talent_v4/services/job_service/transports/base.py @@ -104,7 +104,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 0f57d199..1803ecd1 100644 --- a/google/cloud/talent_v4/services/job_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/job_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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. @@ -103,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 @@ -156,7 +159,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 12638fff..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 @@ -109,6 +109,7 @@ def __init__( 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. @@ -150,6 +151,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 @@ -202,7 +205,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 8c5d88d7..1ac777a7 100644 --- a/google/cloud/talent_v4/services/tenant_service/transports/base.py +++ b/google/cloud/talent_v4/services/tenant_service/transports/base.py @@ -102,7 +102,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 c535708a..4dc57d85 100644 --- a/google/cloud/talent_v4/services/tenant_service/transports/grpc.py +++ b/google/cloud/talent_v4/services/tenant_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 820e3673..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 @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 54295352..b4cf38f7 100644 --- a/google/cloud/talent_v4beta1/services/application_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/application_service/transports/base.py @@ -102,7 +102,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 f32eebdf..1d2b753d 100644 --- a/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/application_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 ce7d8e13..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 @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 f49ddcdf..787483fc 100644 --- a/google/cloud/talent_v4beta1/services/company_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/company_service/transports/base.py @@ -102,7 +102,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 5c9a0b89..ef3cb4db 100644 --- a/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/company_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 e615f8e7..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 @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/talent_v4beta1/services/completion/transports/base.py b/google/cloud/talent_v4beta1/services/completion/transports/base.py index cd4fcba0..77969b7a 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/base.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/base.py @@ -99,7 +99,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. diff --git a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py index 5f84b027..4f416c44 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( 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. @@ -97,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 @@ -149,7 +152,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 c0a6dd7d..98af1d8f 100644 --- a/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py +++ b/google/cloud/talent_v4beta1/services/completion/transports/grpc_asyncio.py @@ -103,6 +103,7 @@ def __init__( 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. @@ -144,6 +145,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 @@ -195,7 +198,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 069cada5..95e666ac 100644 --- a/google/cloud/talent_v4beta1/services/event_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/event_service/transports/base.py @@ -100,7 +100,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 467ca194..f8cc600f 100644 --- a/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/event_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( 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. @@ -98,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 @@ -150,7 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 26dfdd46..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 @@ -104,6 +104,7 @@ def __init__( 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. @@ -145,6 +146,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 @@ -196,7 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 fb769dd4..687c85e8 100644 --- a/google/cloud/talent_v4beta1/services/job_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/job_service/transports/base.py @@ -104,7 +104,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 6371a285..79503e45 100644 --- a/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/job_service/transports/grpc.py @@ -63,6 +63,7 @@ def __init__( 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. @@ -103,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 @@ -156,7 +159,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 d99af105..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 @@ -109,6 +109,7 @@ def __init__( 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. @@ -150,6 +151,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 @@ -202,7 +205,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 8a380697..e444b27e 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/profile_service/transports/base.py @@ -102,7 +102,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 ac20eda5..1bc5089e 100644 --- a/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/profile_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 05bf8cc2..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 @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 77c48040..8fc83e74 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/base.py @@ -102,7 +102,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. 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 ee8ee728..6315e8c4 100644 --- a/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py +++ b/google/cloud/talent_v4beta1/services/tenant_service/transports/grpc.py @@ -61,6 +61,7 @@ def __init__( 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. @@ -101,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 @@ -153,7 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: 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 f6e20bc8..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 @@ -107,6 +107,7 @@ def __init__( 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. @@ -148,6 +149,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 @@ -199,7 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, - always_use_jwt_access=True, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/tests/unit/gapic/talent_v4/test_company_service.py b/tests/unit/gapic/talent_v4/test_company_service.py index de0371b1..d0c2a044 100644 --- a/tests/unit/gapic/talent_v4/test_company_service.py +++ b/tests/unit/gapic/talent_v4/test_company_service.py @@ -133,7 +133,25 @@ def test_company_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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( @@ -2091,10 +2109,7 @@ def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_cl "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_channel_creds, quota_project_id=None, options=[ @@ -2201,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=[ @@ -2251,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=[ diff --git a/tests/unit/gapic/talent_v4/test_completion.py b/tests/unit/gapic/talent_v4/test_completion.py index 3e53b9b1..051e8fdd 100644 --- a/tests/unit/gapic/talent_v4/test_completion.py +++ b/tests/unit/gapic/talent_v4/test_completion.py @@ -120,7 +120,25 @@ def test_completion_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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,]) @@ -873,10 +891,7 @@ def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class): "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_channel_creds, quota_project_id=None, options=[ @@ -978,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=[ @@ -1025,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=[ diff --git a/tests/unit/gapic/talent_v4/test_event_service.py b/tests/unit/gapic/talent_v4/test_event_service.py index 31481d92..434d3aa4 100644 --- a/tests/unit/gapic/talent_v4/test_event_service.py +++ b/tests/unit/gapic/talent_v4/test_event_service.py @@ -121,7 +121,25 @@ def test_event_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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,]) @@ -983,10 +1001,7 @@ def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_clas "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_channel_creds, quota_project_id=None, options=[ @@ -1088,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=[ @@ -1135,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=[ diff --git a/tests/unit/gapic/talent_v4/test_job_service.py b/tests/unit/gapic/talent_v4/test_job_service.py index 8a65b4c1..b488f41a 100644 --- a/tests/unit/gapic/talent_v4/test_job_service.py +++ b/tests/unit/gapic/talent_v4/test_job_service.py @@ -137,7 +137,25 @@ def test_job_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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,]) @@ -3037,10 +3055,7 @@ def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class) "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_channel_creds, quota_project_id=None, options=[ @@ -3142,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=[ @@ -3189,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=[ diff --git a/tests/unit/gapic/talent_v4/test_tenant_service.py b/tests/unit/gapic/talent_v4/test_tenant_service.py index e6d070d5..fadc80d4 100644 --- a/tests/unit/gapic/talent_v4/test_tenant_service.py +++ b/tests/unit/gapic/talent_v4/test_tenant_service.py @@ -130,7 +130,25 @@ def test_tenant_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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( @@ -1926,10 +1944,7 @@ def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_cla "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_channel_creds, quota_project_id=None, options=[ @@ -2034,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=[ @@ -2084,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=[ diff --git a/tests/unit/gapic/talent_v4beta1/test_application_service.py b/tests/unit/gapic/talent_v4beta1/test_application_service.py index 529b93e7..7f6937fb 100644 --- a/tests/unit/gapic/talent_v4beta1/test_application_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_application_service.py @@ -139,7 +139,25 @@ def test_application_service_client_service_account_always_use_jwt(client_class) ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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( @@ -2198,10 +2216,7 @@ def test_application_service_grpc_transport_client_cert_source_for_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_channel_creds, quota_project_id=None, options=[ @@ -2308,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=[ @@ -2358,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=[ diff --git a/tests/unit/gapic/talent_v4beta1/test_company_service.py b/tests/unit/gapic/talent_v4beta1/test_company_service.py index cbfa90a5..ab5c4501 100644 --- a/tests/unit/gapic/talent_v4beta1/test_company_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_company_service.py @@ -135,7 +135,25 @@ def test_company_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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( @@ -2085,10 +2103,7 @@ def test_company_service_grpc_transport_client_cert_source_for_mtls(transport_cl "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_channel_creds, quota_project_id=None, options=[ @@ -2195,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=[ @@ -2245,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=[ diff --git a/tests/unit/gapic/talent_v4beta1/test_completion.py b/tests/unit/gapic/talent_v4beta1/test_completion.py index e697ed57..aba47d51 100644 --- a/tests/unit/gapic/talent_v4beta1/test_completion.py +++ b/tests/unit/gapic/talent_v4beta1/test_completion.py @@ -120,7 +120,25 @@ def test_completion_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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,]) @@ -873,10 +891,7 @@ def test_completion_grpc_transport_client_cert_source_for_mtls(transport_class): "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_channel_creds, quota_project_id=None, options=[ @@ -978,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=[ @@ -1025,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=[ diff --git a/tests/unit/gapic/talent_v4beta1/test_event_service.py b/tests/unit/gapic/talent_v4beta1/test_event_service.py index b24847ed..ecfff6a4 100644 --- a/tests/unit/gapic/talent_v4beta1/test_event_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_event_service.py @@ -121,7 +121,25 @@ def test_event_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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,]) @@ -983,10 +1001,7 @@ def test_event_service_grpc_transport_client_cert_source_for_mtls(transport_clas "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_channel_creds, quota_project_id=None, options=[ @@ -1088,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=[ @@ -1135,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=[ diff --git a/tests/unit/gapic/talent_v4beta1/test_job_service.py b/tests/unit/gapic/talent_v4beta1/test_job_service.py index dc03b773..8f9a3e8e 100644 --- a/tests/unit/gapic/talent_v4beta1/test_job_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_job_service.py @@ -137,7 +137,25 @@ def test_job_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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,]) @@ -3349,10 +3367,7 @@ def test_job_service_grpc_transport_client_cert_source_for_mtls(transport_class) "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_channel_creds, quota_project_id=None, options=[ @@ -3454,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=[ @@ -3501,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=[ diff --git a/tests/unit/gapic/talent_v4beta1/test_profile_service.py b/tests/unit/gapic/talent_v4beta1/test_profile_service.py index e0c302cf..0d8f84c7 100644 --- a/tests/unit/gapic/talent_v4beta1/test_profile_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_profile_service.py @@ -141,7 +141,25 @@ def test_profile_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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( @@ -2340,10 +2358,7 @@ def test_profile_service_grpc_transport_client_cert_source_for_mtls(transport_cl "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_channel_creds, quota_project_id=None, options=[ @@ -2450,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=[ @@ -2500,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=[ diff --git a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py index 7d9650ec..b09d185d 100644 --- a/tests/unit/gapic/talent_v4beta1/test_tenant_service.py +++ b/tests/unit/gapic/talent_v4beta1/test_tenant_service.py @@ -130,7 +130,25 @@ def test_tenant_service_client_service_account_always_use_jwt(client_class): ) as use_jwt: creds = service_account.Credentials(None, None, None) client = client_class(credentials=creds) - use_jwt.assert_called_with(True) + 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( @@ -1978,10 +1996,7 @@ def test_tenant_service_grpc_transport_client_cert_source_for_mtls(transport_cla "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_channel_creds, quota_project_id=None, options=[ @@ -2086,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=[ @@ -2136,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=[ From 9f41fb3ebd20d780cf37614bf45c70d7f5258eae Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 12 Jul 2021 23:24:32 +0000 Subject: [PATCH 26/26] chore: release 2.2.0 (#75) :robot: I have created a release \*beep\* \*boop\* --- ## [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) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 21 +++++++++++++++++++++ setup.py | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) 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/setup.py b/setup.py index 843ac285..29b768a8 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ 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'