diff --git a/.coveragerc b/.coveragerc index 2257f8d2..bfc53359 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,19 +1,3 @@ -# -*- 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. - [run] branch = True diff --git a/.flake8 b/.flake8 index ed931638..29227d4c 100644 --- a/.flake8 +++ b/.flake8 @@ -26,6 +26,7 @@ exclude = *_pb2.py # Standard linting exemptions. + **/.nox/** __pycache__, .git, *.pyc, 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 e68332b2..f8006159 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -15,7 +15,11 @@ set -eo pipefail -cd github/python-kms +if [[ -z "${PROJECT_ROOT:-}" ]]; then + PROJECT_ROOT="github/python-kms" +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/common.cfg b/.kokoro/docs/common.cfg index 02c17705..b393f663 100644 --- a/.kokoro/docs/common.cfg +++ b/.kokoro/docs/common.cfg @@ -30,7 +30,7 @@ env_vars: { env_vars: { key: "V2_STAGING_BUCKET" - value: "docs-staging-v2-staging" + value: "docs-staging-v2" } # It will upload the docker image after successful builds. diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg index 11181078..f20327db 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-kms/.kokoro/build.sh" +} + +# Only run this nox session. +env_vars: { + key: "NOX_SESSION" + value: "docs docfx" +} diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg index 7de5927f..85c2b24e 100644 --- a/.kokoro/samples/python3.6/common.cfg +++ b/.kokoro/samples/python3.6/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.6" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py36" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-kms/.kokoro/test-samples.sh" 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/common.cfg b/.kokoro/samples/python3.7/common.cfg index 91390e2a..8caccfc4 100644 --- a/.kokoro/samples/python3.7/common.cfg +++ b/.kokoro/samples/python3.7/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.7" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py37" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-kms/.kokoro/test-samples.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/common.cfg b/.kokoro/samples/python3.8/common.cfg index 50e47fd4..4ba53601 100644 --- a/.kokoro/samples/python3.8/common.cfg +++ b/.kokoro/samples/python3.8/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.8" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py38" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-kms/.kokoro/test-samples.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..ec13ac11 --- /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-kms + +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 490fbcda..aa5bb054 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,81 +28,19 @@ cd github/python-kms # 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 - -# 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" \ No newline at end of file +exec .kokoro/test-samples-impl.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..32302e48 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,17 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.4.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml +- repo: https://github.com/psf/black + rev: 19.10b0 + hooks: + - id: black +- repo: https://gitlab.com/pycqa/flake8 + 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/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index b3d1f602..039f4368 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,44 +1,95 @@ -# Contributor Code of Conduct +# Code of Conduct -As contributors and maintainers of this project, -and in the interest of fostering an open and welcoming community, -we pledge to respect all people who contribute through reporting issues, -posting feature requests, updating documentation, -submitting pull requests or patches, and other activities. +## Our Pledge -We are committed to making participation in this project -a harassment-free experience for everyone, -regardless of level of experience, gender, gender identity and expression, -sexual orientation, disability, personal appearance, -body size, race, ethnicity, age, religion, or nationality. +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members Examples of unacceptable behavior by participants include: -* The use of sexualized language or imagery -* Personal attacks -* Trolling or insulting/derogatory comments -* Public or private harassment -* Publishing other's private information, -such as physical or electronic -addresses, without explicit permission -* Other unethical or unprofessional conduct. +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct. -By adopting this Code of Conduct, -project maintainers commit themselves to fairly and consistently -applying these principles to every aspect of managing this project. -Project maintainers who do not follow or enforce the Code of Conduct -may be permanently removed from the project team. - -This code of conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. - -Instances of abusive, harassing, or otherwise unacceptable behavior -may be reported by opening an issue -or contacting one or more of the project maintainers. - -This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, -available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index f81b10e7..9076b877 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -21,8 +21,8 @@ In order to add a feature: - The feature must be documented in both the API and narrative documentation. -- The feature must work fully on the following CPython versions: 2.7, - 3.5, 3.6, 3.7 and 3.8 on both UNIX and Windows. +- The feature must work fully on the following CPython versions: + 3.6, 3.7, 3.8 and 3.9 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -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 @@ -80,25 +85,6 @@ We use `nox `__ to instrument our tests. .. nox: https://pypi.org/project/nox/ -Note on Editable Installs / Develop Mode -======================================== - -- As mentioned previously, using ``setuptools`` in `develop mode`_ - or a ``pip`` `editable install`_ is not possible with this - library. This is because this library uses `namespace packages`_. - For context see `Issue #2316`_ and the relevant `PyPA issue`_. - - Since ``editable`` / ``develop`` mode can't be used, packages - need to be installed directly. Hence your changes to the source - tree don't get incorporated into the **already installed** - package. - -.. _namespace packages: https://www.python.org/dev/peps/pep-0420/ -.. _Issue #2316: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2316 -.. _PyPA issue: https://github.com/pypa/packaging-problems/issues/12 -.. _develop mode: https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode -.. _editable install: https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs - ***************************************** I'm getting weird errors... Can you help? ***************************************** @@ -112,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:: -- PEP8 compliance, with exceptions defined in the linter configuration. + $ nox -s blacken + +- 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:: @@ -130,6 +120,16 @@ Coding Style should point to the official ``googleapis`` checkout and the the branch should be the main branch on that remote (``master``). +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + Exceptions to PEP8: - Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for @@ -142,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 @@ -211,25 +216,24 @@ Supported Python Versions We support: -- `Python 3.5`_ - `Python 3.6`_ - `Python 3.7`_ - `Python 3.8`_ +- `Python 3.9`_ -.. _Python 3.5: https://docs.python.org/3.5/ .. _Python 3.6: https://docs.python.org/3.6/ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ Supported versions can be found in our ``noxfile.py`` `config`_. .. _config: https://github.com/googleapis/python-kms/blob/master/noxfile.py -Python 2.7 support is deprecated. All code changes should maintain Python 2.7 compatibility until January 1, 2020. We also explicitly decided to support Python 3 beginning with version -3.5. Reasons for this include: +3.6. Reasons for this include: - Encouraging use of newest versions of Python 3 - Taking the lead of `prominent`_ open-source `projects`_ diff --git a/LICENSE b/LICENSE index a8ee855d..d6456956 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ - Apache License + + Apache License Version 2.0, January 2004 - https://www.apache.org/licenses/ + http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -192,7 +193,7 @@ you may not use this file except in compliance with the License. You may obtain a copy of the License at - https://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/MANIFEST.in b/MANIFEST.in index e9e29d12..e783f4c6 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -16,10 +16,10 @@ # Generated by synthtool. DO NOT EDIT! include README.rst LICENSE -recursive-include google *.json *.proto +recursive-include google *.json *.proto py.typed recursive-include tests * global-exclude *.py[co] global-exclude __pycache__ # Exclude scripts for samples readmegen -prune scripts/readme-gen \ No newline at end of file +prune scripts/readme-gen diff --git a/UPGRADING.md b/UPGRADING.md index bf0b5855..2162b463 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -17,10 +17,10 @@ The 2.0.0 release requires Python 3.6+. 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-kms +python3 -m pip install google-cloud-kms[libcst] ``` * The script `fixup_kms_v1_keywords.py` is shipped with the library. It expects 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/docs/conf.py b/docs/conf.py index 449f5a4f..ecd6773b 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -39,6 +39,7 @@ "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", + "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", @@ -338,10 +339,11 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), - "grpc": ("https://grpc.io/grpc/python/", None), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), } diff --git a/docs/kms_v1/key_management_service.rst b/docs/kms_v1/key_management_service.rst new file mode 100644 index 00000000..405650f0 --- /dev/null +++ b/docs/kms_v1/key_management_service.rst @@ -0,0 +1,11 @@ +KeyManagementService +-------------------------------------- + +.. automodule:: google.cloud.kms_v1.services.key_management_service + :members: + :inherited-members: + + +.. automodule:: google.cloud.kms_v1.services.key_management_service.pagers + :members: + :inherited-members: diff --git a/docs/kms_v1/services.rst b/docs/kms_v1/services.rst index 93db565f..1edbf1d6 100644 --- a/docs/kms_v1/services.rst +++ b/docs/kms_v1/services.rst @@ -1,6 +1,6 @@ Services for Google Cloud Kms v1 API ==================================== +.. toctree:: + :maxdepth: 2 -.. automodule:: google.cloud.kms_v1.services.key_management_service - :members: - :inherited-members: + key_management_service diff --git a/docs/kms_v1/types.rst b/docs/kms_v1/types.rst index 401cef20..fe1026e9 100644 --- a/docs/kms_v1/types.rst +++ b/docs/kms_v1/types.rst @@ -3,3 +3,5 @@ Types for Google Cloud Kms v1 API .. automodule:: google.cloud.kms_v1.types :members: + :undoc-members: + :show-inheritance: diff --git a/google/cloud/kms_v1/services/key_management_service/async_client.py b/google/cloud/kms_v1/services/key_management_service/async_client.py index feb6e574..40c3dbc7 100644 --- a/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -79,10 +79,83 @@ class KeyManagementServiceAsyncClient: ) key_ring_path = staticmethod(KeyManagementServiceClient.key_ring_path) parse_key_ring_path = staticmethod(KeyManagementServiceClient.parse_key_ring_path) + public_key_path = staticmethod(KeyManagementServiceClient.public_key_path) + parse_public_key_path = staticmethod( + KeyManagementServiceClient.parse_public_key_path + ) + + common_billing_account_path = staticmethod( + KeyManagementServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + KeyManagementServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(KeyManagementServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + KeyManagementServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + KeyManagementServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + KeyManagementServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod(KeyManagementServiceClient.common_project_path) + parse_common_project_path = staticmethod( + KeyManagementServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod(KeyManagementServiceClient.common_location_path) + parse_common_location_path = staticmethod( + KeyManagementServiceClient.parse_common_location_path + ) + + @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: + KeyManagementServiceAsyncClient: The constructed client. + """ + return KeyManagementServiceClient.from_service_account_info.__func__(KeyManagementServiceAsyncClient, 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: + KeyManagementServiceAsyncClient: The constructed client. + """ + return KeyManagementServiceClient.from_service_account_file.__func__(KeyManagementServiceAsyncClient, filename, *args, **kwargs) # type: ignore - from_service_account_file = KeyManagementServiceClient.from_service_account_file from_service_account_json = from_service_account_file + @property + def transport(self) -> KeyManagementServiceTransport: + """Return the transport used by the client instance. + + Returns: + KeyManagementServiceTransport: The transport used by the client instance. + """ + return self._client.transport + get_transport_class = functools.partial( type(KeyManagementServiceClient).get_transport_class, type(KeyManagementServiceClient), @@ -150,13 +223,14 @@ async def list_key_rings( Args: - request (:class:`~.service.ListKeyRingsRequest`): + request (:class:`google.cloud.kms_v1.types.ListKeyRingsRequest`): The request object. Request message for [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. parent (:class:`str`): Required. The resource name of the location associated with the [KeyRings][google.cloud.kms.v1.KeyRing], in the format ``projects/*/locations/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -168,7 +242,7 @@ async def list_key_rings( sent along with the request as metadata. Returns: - ~.pagers.ListKeyRingsAsyncPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsAsyncPager: Response message for [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. @@ -179,7 +253,8 @@ async def list_key_rings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -202,10 +277,9 @@ async def list_key_rings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -242,13 +316,14 @@ async def list_crypto_keys( Args: - request (:class:`~.service.ListCryptoKeysRequest`): + request (:class:`google.cloud.kms_v1.types.ListCryptoKeysRequest`): The request object. Request message for [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. parent (:class:`str`): Required. The resource name of the [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the format ``projects/*/locations/*/keyRings/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -260,7 +335,7 @@ async def list_crypto_keys( sent along with the request as metadata. Returns: - ~.pagers.ListCryptoKeysAsyncPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysAsyncPager: Response message for [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. @@ -271,7 +346,8 @@ async def list_crypto_keys( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -294,10 +370,9 @@ async def list_crypto_keys( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -334,7 +409,7 @@ async def list_crypto_key_versions( Args: - request (:class:`~.service.ListCryptoKeyVersionsRequest`): + request (:class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest`): The request object. Request message for [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. parent (:class:`str`): @@ -342,6 +417,7 @@ async def list_crypto_key_versions( [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in the format ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -353,7 +429,7 @@ async def list_crypto_key_versions( sent along with the request as metadata. Returns: - ~.pagers.ListCryptoKeyVersionsAsyncPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager: Response message for [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. @@ -364,7 +440,8 @@ async def list_crypto_key_versions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -387,10 +464,9 @@ async def list_crypto_key_versions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -427,13 +503,14 @@ async def list_import_jobs( Args: - request (:class:`~.service.ListImportJobsRequest`): + request (:class:`google.cloud.kms_v1.types.ListImportJobsRequest`): The request object. Request message for [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. parent (:class:`str`): Required. The resource name of the [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the format ``projects/*/locations/*/keyRings/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -445,7 +522,7 @@ async def list_import_jobs( sent along with the request as metadata. Returns: - ~.pagers.ListImportJobsAsyncPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsAsyncPager: Response message for [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. @@ -456,7 +533,8 @@ async def list_import_jobs( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -479,10 +557,9 @@ async def list_import_jobs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -520,12 +597,13 @@ async def get_key_ring( Args: - request (:class:`~.service.GetKeyRingRequest`): + request (:class:`google.cloud.kms_v1.types.GetKeyRingRequest`): The request object. Request message for [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. name (:class:`str`): Required. The [name][google.cloud.kms.v1.KeyRing.name] of the [KeyRing][google.cloud.kms.v1.KeyRing] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -537,7 +615,7 @@ async def get_key_ring( sent along with the request as metadata. Returns: - ~.resources.KeyRing: + google.cloud.kms_v1.types.KeyRing: A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. @@ -546,7 +624,8 @@ async def get_key_ring( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -569,10 +648,9 @@ async def get_key_ring( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -606,13 +684,14 @@ async def get_crypto_key( Args: - request (:class:`~.service.GetCryptoKeyRequest`): + request (:class:`google.cloud.kms_v1.types.GetCryptoKeyRequest`): The request object. Request message for [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. name (:class:`str`): Required. The [name][google.cloud.kms.v1.CryptoKey.name] of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -624,22 +703,22 @@ async def get_crypto_key( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -662,10 +741,9 @@ async def get_crypto_key( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -697,7 +775,7 @@ async def get_crypto_key_version( Args: - request (:class:`~.service.GetCryptoKeyVersionRequest`): + request (:class:`google.cloud.kms_v1.types.GetCryptoKeyVersionRequest`): The request object. Request message for [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. name (:class:`str`): @@ -705,6 +783,7 @@ async def get_crypto_key_version( [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -716,28 +795,27 @@ async def get_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -760,10 +838,9 @@ async def get_crypto_key_version( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -800,7 +877,7 @@ async def get_public_key( Args: - request (:class:`~.service.GetPublicKeyRequest`): + request (:class:`google.cloud.kms_v1.types.GetPublicKeyRequest`): The request object. Request message for [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. name (:class:`str`): @@ -808,6 +885,7 @@ async def get_public_key( [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] public key to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -819,17 +897,16 @@ async def get_public_key( sent along with the request as metadata. Returns: - ~.resources.PublicKey: - The public key for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Obtained via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + google.cloud.kms_v1.types.PublicKey: + The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -852,10 +929,9 @@ async def get_public_key( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -887,13 +963,14 @@ async def get_import_job( Args: - request (:class:`~.service.GetImportJobRequest`): + request (:class:`google.cloud.kms_v1.types.GetImportJobRequest`): The request object. Request message for [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. name (:class:`str`): Required. The [name][google.cloud.kms.v1.ImportJob.name] of the [ImportJob][google.cloud.kms.v1.ImportJob] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -905,58 +982,59 @@ async def get_import_job( sent along with the request as metadata. Returns: - ~.resources.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be - used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", which - is a public/private key pair. You use the wrapping key - to encrypt (also known as wrap) the pre-existing key - material to protect it during the import process. The - nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set - to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be used - to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 - days after it is created. Once expired, Cloud KMS will - no longer be able to import or unwrap any key material - that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. + google.cloud.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -979,10 +1057,9 @@ async def get_import_job( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1016,25 +1093,28 @@ async def create_key_ring( Args: - request (:class:`~.service.CreateKeyRingRequest`): + request (:class:`google.cloud.kms_v1.types.CreateKeyRingRequest`): The request object. Request message for [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. parent (:class:`str`): Required. The resource name of the location associated with the [KeyRings][google.cloud.kms.v1.KeyRing], in the format ``projects/*/locations/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. key_ring_id (:class:`str`): Required. It must be unique within a location and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` + This corresponds to the ``key_ring_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - key_ring (:class:`~.resources.KeyRing`): + key_ring (:class:`google.cloud.kms_v1.types.KeyRing`): Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with initial field values. + This corresponds to the ``key_ring`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1046,7 +1126,7 @@ async def create_key_ring( sent along with the request as metadata. Returns: - ~.resources.KeyRing: + google.cloud.kms_v1.types.KeyRing: A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. @@ -1055,7 +1135,8 @@ async def create_key_ring( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, key_ring_id, key_ring]): + has_flattened_params = any([parent, key_ring_id, key_ring]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1082,10 +1163,9 @@ async def create_key_ring( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1123,25 +1203,28 @@ async def create_crypto_key( Args: - request (:class:`~.service.CreateCryptoKeyRequest`): + request (:class:`google.cloud.kms_v1.types.CreateCryptoKeyRequest`): The request object. Request message for [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. parent (:class:`str`): Required. The [name][google.cloud.kms.v1.KeyRing.name] of the KeyRing associated with the [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. crypto_key_id (:class:`str`): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` + This corresponds to the ``crypto_key_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - crypto_key (:class:`~.resources.CryptoKey`): + crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with initial field values. + This corresponds to the ``crypto_key`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1153,22 +1236,22 @@ async def create_crypto_key( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, crypto_key_id, crypto_key]): + has_flattened_params = any([parent, crypto_key_id, crypto_key]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1195,10 +1278,9 @@ async def create_crypto_key( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1237,7 +1319,7 @@ async def create_crypto_key_version( Args: - request (:class:`~.service.CreateCryptoKeyVersionRequest`): + request (:class:`google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest`): The request object. Request message for [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. parent (:class:`str`): @@ -1245,13 +1327,15 @@ async def create_crypto_key_version( of the [CryptoKey][google.cloud.kms.v1.CryptoKey] associated with the [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - crypto_key_version (:class:`~.resources.CryptoKeyVersion`): + crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): Required. A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with initial field values. + This corresponds to the ``crypto_key_version`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1263,28 +1347,27 @@ async def create_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, crypto_key_version]): + has_flattened_params = any([parent, crypto_key_version]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1338,7 +1421,7 @@ async def import_crypto_key_version( Args: - request (:class:`~.service.ImportCryptoKeyVersionRequest`): + request (:class:`google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest`): The request object. Request message for [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. @@ -1349,22 +1432,20 @@ async def import_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. @@ -1410,25 +1491,28 @@ async def create_import_job( Args: - request (:class:`~.service.CreateImportJobRequest`): + request (:class:`google.cloud.kms_v1.types.CreateImportJobRequest`): The request object. Request message for [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. parent (:class:`str`): Required. The [name][google.cloud.kms.v1.KeyRing.name] of the [KeyRing][google.cloud.kms.v1.KeyRing] associated with the [ImportJobs][google.cloud.kms.v1.ImportJob]. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. import_job_id (:class:`str`): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` + This corresponds to the ``import_job_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - import_job (:class:`~.resources.ImportJob`): + import_job (:class:`google.cloud.kms_v1.types.ImportJob`): Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field values. + This corresponds to the ``import_job`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1440,58 +1524,59 @@ async def create_import_job( sent along with the request as metadata. Returns: - ~.resources.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be - used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", which - is a public/private key pair. You use the wrapping key - to encrypt (also known as wrap) the pre-existing key - material to protect it during the import process. The - nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set - to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be used - to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 - days after it is created. Once expired, Cloud KMS will - no longer be able to import or unwrap any key material - that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. + google.cloud.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, import_job_id, import_job]): + has_flattened_params = any([parent, import_job_id, import_job]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1518,10 +1603,9 @@ async def create_import_job( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1553,18 +1637,20 @@ async def update_crypto_key( Args: - request (:class:`~.service.UpdateCryptoKeyRequest`): + request (:class:`google.cloud.kms_v1.types.UpdateCryptoKeyRequest`): The request object. Request message for [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - crypto_key (:class:`~.resources.CryptoKey`): + crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] with updated values. + This corresponds to the ``crypto_key`` 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`): Required. List of fields to be updated in this request. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1576,22 +1662,22 @@ async def update_crypto_key( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([crypto_key, update_mask]): + has_flattened_params = any([crypto_key, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1616,10 +1702,9 @@ async def update_crypto_key( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1666,19 +1751,21 @@ async def update_crypto_key_version( Args: - request (:class:`~.service.UpdateCryptoKeyVersionRequest`): + request (:class:`google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest`): The request object. Request message for [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - crypto_key_version (:class:`~.resources.CryptoKeyVersion`): + crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): Required. [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with updated values. + This corresponds to the ``crypto_key_version`` 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`): Required. List of fields to be updated in this request. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1690,28 +1777,27 @@ async def update_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([crypto_key_version, update_mask]): + has_flattened_params = any([crypto_key_version, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1736,10 +1822,9 @@ async def update_crypto_key_version( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1777,7 +1862,7 @@ async def encrypt( Args: - request (:class:`~.service.EncryptRequest`): + request (:class:`google.cloud.kms_v1.types.EncryptRequest`): The request object. Request message for [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. name (:class:`str`): @@ -1789,6 +1874,7 @@ async def encrypt( If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is specified, the server will use its [primary version][google.cloud.kms.v1.CryptoKey.primary]. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1805,6 +1891,7 @@ async def encrypt( combined length of the plaintext and additional_authenticated_data fields must be no larger than 8KiB. + This corresponds to the ``plaintext`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1816,7 +1903,7 @@ async def encrypt( sent along with the request as metadata. Returns: - ~.service.EncryptResponse: + google.cloud.kms_v1.types.EncryptResponse: Response message for [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. @@ -1824,7 +1911,8 @@ async def encrypt( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, plaintext]): + has_flattened_params = any([name, plaintext]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1849,10 +1937,9 @@ async def encrypt( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1888,7 +1975,7 @@ async def decrypt( Args: - request (:class:`~.service.DecryptRequest`): + request (:class:`google.cloud.kms_v1.types.DecryptRequest`): The request object. Request message for [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. name (:class:`str`): @@ -1896,12 +1983,14 @@ async def decrypt( [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for decryption. The server will choose the appropriate version. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. ciphertext (:class:`bytes`): Required. The encrypted data originally returned in [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + This corresponds to the ``ciphertext`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1913,7 +2002,7 @@ async def decrypt( sent along with the request as metadata. Returns: - ~.service.DecryptResponse: + google.cloud.kms_v1.types.DecryptResponse: Response message for [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. @@ -1921,7 +2010,8 @@ async def decrypt( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, ciphertext]): + has_flattened_params = any([name, ciphertext]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -1946,10 +2036,9 @@ async def decrypt( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -1986,21 +2075,23 @@ async def asymmetric_sign( Args: - request (:class:`~.service.AsymmetricSignRequest`): + request (:class:`google.cloud.kms_v1.types.AsymmetricSignRequest`): The request object. Request message for [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. name (:class:`str`): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for signing. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - digest (:class:`~.service.Digest`): + digest (:class:`google.cloud.kms_v1.types.Digest`): Required. The digest of the data to sign. The digest must be produced with the same digest algorithm as specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + This corresponds to the ``digest`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2012,7 +2103,7 @@ async def asymmetric_sign( sent along with the request as metadata. Returns: - ~.service.AsymmetricSignResponse: + google.cloud.kms_v1.types.AsymmetricSignResponse: Response message for [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. @@ -2020,7 +2111,8 @@ async def asymmetric_sign( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, digest]): + has_flattened_params = any([name, digest]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -2045,10 +2137,9 @@ async def asymmetric_sign( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -2086,13 +2177,14 @@ async def asymmetric_decrypt( Args: - request (:class:`~.service.AsymmetricDecryptRequest`): + request (:class:`google.cloud.kms_v1.types.AsymmetricDecryptRequest`): The request object. Request message for [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. name (:class:`str`): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for decryption. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2100,6 +2192,7 @@ async def asymmetric_decrypt( Required. The data encrypted with the named [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s public key using OAEP. + This corresponds to the ``ciphertext`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2111,7 +2204,7 @@ async def asymmetric_decrypt( sent along with the request as metadata. Returns: - ~.service.AsymmetricDecryptResponse: + google.cloud.kms_v1.types.AsymmetricDecryptResponse: Response message for [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. @@ -2119,7 +2212,8 @@ async def asymmetric_decrypt( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, ciphertext]): + has_flattened_params = any([name, ciphertext]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -2144,10 +2238,9 @@ async def asymmetric_decrypt( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -2183,12 +2276,13 @@ async def update_crypto_key_primary_version( Args: - request (:class:`~.service.UpdateCryptoKeyPrimaryVersionRequest`): + request (:class:`google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest`): The request object. Request message for [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. name (:class:`str`): Required. The resource name of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2196,6 +2290,7 @@ async def update_crypto_key_primary_version( Required. The id of the child [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use as primary. + This corresponds to the ``crypto_key_version_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2207,22 +2302,22 @@ async def update_crypto_key_primary_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, crypto_key_version_id]): + has_flattened_params = any([name, crypto_key_version_id]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -2247,10 +2342,9 @@ async def update_crypto_key_primary_version( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -2301,13 +2395,14 @@ async def destroy_crypto_key_version( Args: - request (:class:`~.service.DestroyCryptoKeyVersionRequest`): + request (:class:`google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest`): The request object. Request message for [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. name (:class:`str`): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to destroy. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2319,28 +2414,27 @@ async def destroy_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -2363,10 +2457,9 @@ async def destroy_crypto_key_version( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, @@ -2408,13 +2501,14 @@ async def restore_crypto_key_version( Args: - request (:class:`~.service.RestoreCryptoKeyVersionRequest`): + request (:class:`google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest`): The request object. Request message for [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. name (:class:`str`): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to restore. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2426,28 +2520,27 @@ async def restore_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." @@ -2470,10 +2563,9 @@ async def restore_crypto_key_version( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=DEFAULT_CLIENT_INFO, diff --git a/google/cloud/kms_v1/services/key_management_service/client.py b/google/cloud/kms_v1/services/key_management_service/client.py index 8e6aff4f..f0c534eb 100644 --- a/google/cloud/kms_v1/services/key_management_service/client.py +++ b/google/cloud/kms_v1/services/key_management_service/client.py @@ -19,10 +19,10 @@ from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +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 gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore @@ -133,6 +133,23 @@ 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: + KeyManagementServiceClient: 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 @@ -146,7 +163,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. + KeyManagementServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials @@ -154,6 +171,15 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> KeyManagementServiceTransport: + """Return the transport used by the client instance. + + Returns: + KeyManagementServiceTransport: The transport used by the client instance. + """ + return self._transport + @staticmethod def crypto_key_path( project: str, location: str, key_ring: str, crypto_key: str, @@ -238,12 +264,97 @@ def parse_key_ring_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def public_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + crypto_key_version: str, + ) -> str: + """Return a fully-qualified public_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + + @staticmethod + def parse_public_key_path(path: str) -> Dict[str, str]: + """Parse a public_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)/publicKey$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, KeyManagementServiceTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, KeyManagementServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the key management service client. @@ -255,11 +366,11 @@ 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, ~.KeyManagementServiceTransport]): The + transport (Union[str, KeyManagementServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. + 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 environment variable can also be used to override the endpoint: @@ -274,10 +385,10 @@ def __init__( not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. - 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: @@ -285,30 +396,26 @@ def __init__( creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool( 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: @@ -351,7 +458,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, ) @@ -369,13 +476,14 @@ def list_key_rings( Args: - request (:class:`~.service.ListKeyRingsRequest`): + request (google.cloud.kms_v1.types.ListKeyRingsRequest): The request object. Request message for [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - parent (:class:`str`): + parent (str): Required. The resource name of the location associated with the [KeyRings][google.cloud.kms.v1.KeyRing], in the format ``projects/*/locations/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -387,7 +495,7 @@ def list_key_rings( sent along with the request as metadata. Returns: - ~.pagers.ListKeyRingsPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsPager: Response message for [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. @@ -453,13 +561,14 @@ def list_crypto_keys( Args: - request (:class:`~.service.ListCryptoKeysRequest`): + request (google.cloud.kms_v1.types.ListCryptoKeysRequest): The request object. Request message for [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - parent (:class:`str`): + parent (str): Required. The resource name of the [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the format ``projects/*/locations/*/keyRings/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -471,7 +580,7 @@ def list_crypto_keys( sent along with the request as metadata. Returns: - ~.pagers.ListCryptoKeysPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysPager: Response message for [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. @@ -537,14 +646,15 @@ def list_crypto_key_versions( Args: - request (:class:`~.service.ListCryptoKeyVersionsRequest`): + request (google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest): The request object. Request message for [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - parent (:class:`str`): + parent (str): Required. The resource name of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in the format ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -556,7 +666,7 @@ def list_crypto_key_versions( sent along with the request as metadata. Returns: - ~.pagers.ListCryptoKeyVersionsPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsPager: Response message for [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. @@ -622,13 +732,14 @@ def list_import_jobs( Args: - request (:class:`~.service.ListImportJobsRequest`): + request (google.cloud.kms_v1.types.ListImportJobsRequest): The request object. Request message for [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - parent (:class:`str`): + parent (str): Required. The resource name of the [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the format ``projects/*/locations/*/keyRings/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -640,7 +751,7 @@ def list_import_jobs( sent along with the request as metadata. Returns: - ~.pagers.ListImportJobsPager: + google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsPager: Response message for [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. @@ -707,12 +818,13 @@ def get_key_ring( Args: - request (:class:`~.service.GetKeyRingRequest`): + request (google.cloud.kms_v1.types.GetKeyRingRequest): The request object. Request message for [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - name (:class:`str`): + name (str): Required. The [name][google.cloud.kms.v1.KeyRing.name] of the [KeyRing][google.cloud.kms.v1.KeyRing] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -724,7 +836,7 @@ def get_key_ring( sent along with the request as metadata. Returns: - ~.resources.KeyRing: + google.cloud.kms_v1.types.KeyRing: A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. @@ -785,13 +897,14 @@ def get_crypto_key( Args: - request (:class:`~.service.GetCryptoKeyRequest`): + request (google.cloud.kms_v1.types.GetCryptoKeyRequest): The request object. Request message for [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - name (:class:`str`): + name (str): Required. The [name][google.cloud.kms.v1.CryptoKey.name] of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -803,16 +916,15 @@ def get_crypto_key( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. @@ -868,14 +980,15 @@ def get_crypto_key_version( Args: - request (:class:`~.service.GetCryptoKeyVersionRequest`): + request (google.cloud.kms_v1.types.GetCryptoKeyVersionRequest): The request object. Request message for [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - name (:class:`str`): + name (str): Required. The [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -887,22 +1000,20 @@ def get_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. @@ -963,14 +1074,15 @@ def get_public_key( Args: - request (:class:`~.service.GetPublicKeyRequest`): + request (google.cloud.kms_v1.types.GetPublicKeyRequest): The request object. Request message for [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - name (:class:`str`): + name (str): Required. The [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] public key to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -982,11 +1094,9 @@ def get_public_key( sent along with the request as metadata. Returns: - ~.resources.PublicKey: - The public key for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Obtained via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + google.cloud.kms_v1.types.PublicKey: + The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. """ # Create or coerce a protobuf request object. @@ -1042,13 +1152,14 @@ def get_import_job( Args: - request (:class:`~.service.GetImportJobRequest`): + request (google.cloud.kms_v1.types.GetImportJobRequest): The request object. Request message for [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - name (:class:`str`): + name (str): Required. The [name][google.cloud.kms.v1.ImportJob.name] of the [ImportJob][google.cloud.kms.v1.ImportJob] to get. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1060,52 +1171,52 @@ def get_import_job( sent along with the request as metadata. Returns: - ~.resources.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be - used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", which - is a public/private key pair. You use the wrapping key - to encrypt (also known as wrap) the pre-existing key - material to protect it during the import process. The - nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set - to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be used - to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 - days after it is created. Once expired, Cloud KMS will - no longer be able to import or unwrap any key material - that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. + google.cloud.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). """ # Create or coerce a protobuf request object. @@ -1163,25 +1274,28 @@ def create_key_ring( Args: - request (:class:`~.service.CreateKeyRingRequest`): + request (google.cloud.kms_v1.types.CreateKeyRingRequest): The request object. Request message for [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - parent (:class:`str`): + parent (str): Required. The resource name of the location associated with the [KeyRings][google.cloud.kms.v1.KeyRing], in the format ``projects/*/locations/*``. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - key_ring_id (:class:`str`): + key_ring_id (str): Required. It must be unique within a location and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` + This corresponds to the ``key_ring_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - key_ring (:class:`~.resources.KeyRing`): + key_ring (google.cloud.kms_v1.types.KeyRing): Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with initial field values. + This corresponds to the ``key_ring`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1193,7 +1307,7 @@ def create_key_ring( sent along with the request as metadata. Returns: - ~.resources.KeyRing: + google.cloud.kms_v1.types.KeyRing: A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. @@ -1262,25 +1376,28 @@ def create_crypto_key( Args: - request (:class:`~.service.CreateCryptoKeyRequest`): + request (google.cloud.kms_v1.types.CreateCryptoKeyRequest): The request object. Request message for [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - parent (:class:`str`): + parent (str): Required. The [name][google.cloud.kms.v1.KeyRing.name] of the KeyRing associated with the [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - crypto_key_id (:class:`str`): + crypto_key_id (str): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` + This corresponds to the ``crypto_key_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - crypto_key (:class:`~.resources.CryptoKey`): + crypto_key (google.cloud.kms_v1.types.CryptoKey): Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with initial field values. + This corresponds to the ``crypto_key`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1292,16 +1409,15 @@ def create_crypto_key( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. @@ -1368,21 +1484,23 @@ def create_crypto_key_version( Args: - request (:class:`~.service.CreateCryptoKeyVersionRequest`): + request (google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest): The request object. Request message for [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - parent (:class:`str`): + parent (str): Required. The [name][google.cloud.kms.v1.CryptoKey.name] of the [CryptoKey][google.cloud.kms.v1.CryptoKey] associated with the [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - crypto_key_version (:class:`~.resources.CryptoKeyVersion`): + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): Required. A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with initial field values. + This corresponds to the ``crypto_key_version`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1394,22 +1512,20 @@ def create_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. @@ -1473,7 +1589,7 @@ def import_crypto_key_version( Args: - request (:class:`~.service.ImportCryptoKeyVersionRequest`): + request (google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest): The request object. Request message for [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. @@ -1484,22 +1600,20 @@ def import_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. @@ -1548,25 +1662,28 @@ def create_import_job( Args: - request (:class:`~.service.CreateImportJobRequest`): + request (google.cloud.kms_v1.types.CreateImportJobRequest): The request object. Request message for [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - parent (:class:`str`): + parent (str): Required. The [name][google.cloud.kms.v1.KeyRing.name] of the [KeyRing][google.cloud.kms.v1.KeyRing] associated with the [ImportJobs][google.cloud.kms.v1.ImportJob]. + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - import_job_id (:class:`str`): + import_job_id (str): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` + This corresponds to the ``import_job_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - import_job (:class:`~.resources.ImportJob`): + import_job (google.cloud.kms_v1.types.ImportJob): Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field values. + This corresponds to the ``import_job`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1578,52 +1695,52 @@ def create_import_job( sent along with the request as metadata. Returns: - ~.resources.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be - used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", which - is a public/private key pair. You use the wrapping key - to encrypt (also known as wrap) the pre-existing key - material to protect it during the import process. The - nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set - to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be used - to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 - days after it is created. Once expired, Cloud KMS will - no longer be able to import or unwrap any key material - that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. + google.cloud.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). """ # Create or coerce a protobuf request object. @@ -1683,18 +1800,20 @@ def update_crypto_key( Args: - request (:class:`~.service.UpdateCryptoKeyRequest`): + request (google.cloud.kms_v1.types.UpdateCryptoKeyRequest): The request object. Request message for [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - crypto_key (:class:`~.resources.CryptoKey`): + crypto_key (google.cloud.kms_v1.types.CryptoKey): Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] with updated values. + This corresponds to the ``crypto_key`` 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): Required. List of fields to be updated in this request. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1706,16 +1825,15 @@ def update_crypto_key( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. @@ -1788,19 +1906,21 @@ def update_crypto_key_version( Args: - request (:class:`~.service.UpdateCryptoKeyVersionRequest`): + request (google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest): The request object. Request message for [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - crypto_key_version (:class:`~.resources.CryptoKeyVersion`): + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): Required. [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with updated values. + This corresponds to the ``crypto_key_version`` 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): Required. List of fields to be updated in this request. + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1812,22 +1932,20 @@ def update_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. @@ -1893,10 +2011,10 @@ def encrypt( Args: - request (:class:`~.service.EncryptRequest`): + request (google.cloud.kms_v1.types.EncryptRequest): The request object. Request message for [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - name (:class:`str`): + name (str): Required. The resource name of the [CryptoKey][google.cloud.kms.v1.CryptoKey] or [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] @@ -1905,10 +2023,11 @@ def encrypt( If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is specified, the server will use its [primary version][google.cloud.kms.v1.CryptoKey.primary]. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - plaintext (:class:`bytes`): + plaintext (bytes): Required. The data to encrypt. Must be no larger than 64KiB. @@ -1921,6 +2040,7 @@ def encrypt( combined length of the plaintext and additional_authenticated_data fields must be no larger than 8KiB. + This corresponds to the ``plaintext`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1932,7 +2052,7 @@ def encrypt( sent along with the request as metadata. Returns: - ~.service.EncryptResponse: + google.cloud.kms_v1.types.EncryptResponse: Response message for [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. @@ -1996,20 +2116,22 @@ def decrypt( Args: - request (:class:`~.service.DecryptRequest`): + request (google.cloud.kms_v1.types.DecryptRequest): The request object. Request message for [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - name (:class:`str`): + name (str): Required. The resource name of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for decryption. The server will choose the appropriate version. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - ciphertext (:class:`bytes`): + ciphertext (bytes): Required. The encrypted data originally returned in [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + This corresponds to the ``ciphertext`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2021,7 +2143,7 @@ def decrypt( sent along with the request as metadata. Returns: - ~.service.DecryptResponse: + google.cloud.kms_v1.types.DecryptResponse: Response message for [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. @@ -2086,21 +2208,23 @@ def asymmetric_sign( Args: - request (:class:`~.service.AsymmetricSignRequest`): + request (google.cloud.kms_v1.types.AsymmetricSignRequest): The request object. Request message for [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - name (:class:`str`): + name (str): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for signing. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - digest (:class:`~.service.Digest`): + digest (google.cloud.kms_v1.types.Digest): Required. The digest of the data to sign. The digest must be produced with the same digest algorithm as specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + This corresponds to the ``digest`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2112,7 +2236,7 @@ def asymmetric_sign( sent along with the request as metadata. Returns: - ~.service.AsymmetricSignResponse: + google.cloud.kms_v1.types.AsymmetricSignResponse: Response message for [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. @@ -2178,20 +2302,22 @@ def asymmetric_decrypt( Args: - request (:class:`~.service.AsymmetricDecryptRequest`): + request (google.cloud.kms_v1.types.AsymmetricDecryptRequest): The request object. Request message for [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - name (:class:`str`): + name (str): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for decryption. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - ciphertext (:class:`bytes`): + ciphertext (bytes): Required. The data encrypted with the named [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s public key using OAEP. + This corresponds to the ``ciphertext`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2203,7 +2329,7 @@ def asymmetric_decrypt( sent along with the request as metadata. Returns: - ~.service.AsymmetricDecryptResponse: + google.cloud.kms_v1.types.AsymmetricDecryptResponse: Response message for [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. @@ -2267,19 +2393,21 @@ def update_crypto_key_primary_version( Args: - request (:class:`~.service.UpdateCryptoKeyPrimaryVersionRequest`): + request (google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest): The request object. Request message for [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - name (:class:`str`): + name (str): Required. The resource name of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - crypto_key_version_id (:class:`str`): + crypto_key_version_id (str): Required. The id of the child [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use as primary. + This corresponds to the ``crypto_key_version_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2291,16 +2419,15 @@ def update_crypto_key_primary_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic + operations. - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. """ # Create or coerce a protobuf request object. @@ -2379,13 +2506,14 @@ def destroy_crypto_key_version( Args: - request (:class:`~.service.DestroyCryptoKeyVersionRequest`): + request (google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest): The request object. Request message for [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - name (:class:`str`): + name (str): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to destroy. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2397,22 +2525,20 @@ def destroy_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. @@ -2480,13 +2606,14 @@ def restore_crypto_key_version( Args: - request (:class:`~.service.RestoreCryptoKeyVersionRequest`): + request (google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest): The request object. Request message for [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - name (:class:`str`): + name (str): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to restore. + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2498,22 +2625,20 @@ def restore_crypto_key_version( sent along with the request as metadata. Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/kms_v1/services/key_management_service/pagers.py b/google/cloud/kms_v1/services/key_management_service/pagers.py index c888e2e9..e6902213 100644 --- a/google/cloud/kms_v1/services/key_management_service/pagers.py +++ b/google/cloud/kms_v1/services/key_management_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.kms_v1.types import resources from google.cloud.kms_v1.types import service @@ -25,7 +34,7 @@ class ListKeyRingsPager: """A pager for iterating through ``list_key_rings`` requests. This class thinly wraps an initial - :class:`~.service.ListKeyRingsResponse` object, and + :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and provides an ``__iter__`` method to iterate through its ``key_rings`` field. @@ -34,7 +43,7 @@ class ListKeyRingsPager: through the ``key_rings`` field on the corresponding responses. - All the usual :class:`~.service.ListKeyRingsResponse` + All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` 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:`~.service.ListKeyRingsRequest`): + request (google.cloud.kms_v1.types.ListKeyRingsRequest): The initial request object. - response (:class:`~.service.ListKeyRingsResponse`): + response (google.cloud.kms_v1.types.ListKeyRingsResponse): 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 ListKeyRingsAsyncPager: """A pager for iterating through ``list_key_rings`` requests. This class thinly wraps an initial - :class:`~.service.ListKeyRingsResponse` object, and + :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and provides an ``__aiter__`` method to iterate through its ``key_rings`` field. @@ -96,7 +105,7 @@ class ListKeyRingsAsyncPager: through the ``key_rings`` field on the corresponding responses. - All the usual :class:`~.service.ListKeyRingsResponse` + All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` 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:`~.service.ListKeyRingsRequest`): + request (google.cloud.kms_v1.types.ListKeyRingsRequest): The initial request object. - response (:class:`~.service.ListKeyRingsResponse`): + response (google.cloud.kms_v1.types.ListKeyRingsResponse): 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 ListCryptoKeysPager: """A pager for iterating through ``list_crypto_keys`` requests. This class thinly wraps an initial - :class:`~.service.ListCryptoKeysResponse` object, and + :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and provides an ``__iter__`` method to iterate through its ``crypto_keys`` field. @@ -162,7 +171,7 @@ class ListCryptoKeysPager: through the ``crypto_keys`` field on the corresponding responses. - All the usual :class:`~.service.ListCryptoKeysResponse` + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` 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:`~.service.ListCryptoKeysRequest`): + request (google.cloud.kms_v1.types.ListCryptoKeysRequest): The initial request object. - response (:class:`~.service.ListCryptoKeysResponse`): + response (google.cloud.kms_v1.types.ListCryptoKeysResponse): 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 ListCryptoKeysAsyncPager: """A pager for iterating through ``list_crypto_keys`` requests. This class thinly wraps an initial - :class:`~.service.ListCryptoKeysResponse` object, and + :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and provides an ``__aiter__`` method to iterate through its ``crypto_keys`` field. @@ -224,7 +233,7 @@ class ListCryptoKeysAsyncPager: through the ``crypto_keys`` field on the corresponding responses. - All the usual :class:`~.service.ListCryptoKeysResponse` + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` 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:`~.service.ListCryptoKeysRequest`): + request (google.cloud.kms_v1.types.ListCryptoKeysRequest): The initial request object. - response (:class:`~.service.ListCryptoKeysResponse`): + response (google.cloud.kms_v1.types.ListCryptoKeysResponse): 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 ListCryptoKeyVersionsPager: """A pager for iterating through ``list_crypto_key_versions`` requests. This class thinly wraps an initial - :class:`~.service.ListCryptoKeyVersionsResponse` object, and + :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and provides an ``__iter__`` method to iterate through its ``crypto_key_versions`` field. @@ -290,7 +299,7 @@ class ListCryptoKeyVersionsPager: through the ``crypto_key_versions`` field on the corresponding responses. - All the usual :class:`~.service.ListCryptoKeyVersionsResponse` + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` 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:`~.service.ListCryptoKeyVersionsRequest`): + request (google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest): The initial request object. - response (:class:`~.service.ListCryptoKeyVersionsResponse`): + response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): 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 ListCryptoKeyVersionsAsyncPager: """A pager for iterating through ``list_crypto_key_versions`` requests. This class thinly wraps an initial - :class:`~.service.ListCryptoKeyVersionsResponse` object, and + :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and provides an ``__aiter__`` method to iterate through its ``crypto_key_versions`` field. @@ -352,7 +361,7 @@ class ListCryptoKeyVersionsAsyncPager: through the ``crypto_key_versions`` field on the corresponding responses. - All the usual :class:`~.service.ListCryptoKeyVersionsResponse` + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` 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:`~.service.ListCryptoKeyVersionsRequest`): + request (google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest): The initial request object. - response (:class:`~.service.ListCryptoKeyVersionsResponse`): + response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -409,7 +418,7 @@ class ListImportJobsPager: """A pager for iterating through ``list_import_jobs`` requests. This class thinly wraps an initial - :class:`~.service.ListImportJobsResponse` object, and + :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and provides an ``__iter__`` method to iterate through its ``import_jobs`` field. @@ -418,7 +427,7 @@ class ListImportJobsPager: through the ``import_jobs`` field on the corresponding responses. - All the usual :class:`~.service.ListImportJobsResponse` + All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -436,9 +445,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.service.ListImportJobsRequest`): + request (google.cloud.kms_v1.types.ListImportJobsRequest): The initial request object. - response (:class:`~.service.ListImportJobsResponse`): + response (google.cloud.kms_v1.types.ListImportJobsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. @@ -471,7 +480,7 @@ class ListImportJobsAsyncPager: """A pager for iterating through ``list_import_jobs`` requests. This class thinly wraps an initial - :class:`~.service.ListImportJobsResponse` object, and + :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and provides an ``__aiter__`` method to iterate through its ``import_jobs`` field. @@ -480,7 +489,7 @@ class ListImportJobsAsyncPager: through the ``import_jobs`` field on the corresponding responses. - All the usual :class:`~.service.ListImportJobsResponse` + All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ @@ -498,9 +507,9 @@ def __init__( Args: method (Callable): The method that was originally called, and which instantiated this pager. - request (:class:`~.service.ListImportJobsRequest`): + request (google.cloud.kms_v1.types.ListImportJobsRequest): The initial request object. - response (:class:`~.service.ListImportJobsResponse`): + response (google.cloud.kms_v1.types.ListImportJobsResponse): 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/kms_v1/services/key_management_service/transports/__init__.py b/google/cloud/kms_v1/services/key_management_service/transports/__init__.py index 7b89668a..4ee693ad 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/__init__.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/__init__.py @@ -30,7 +30,6 @@ _transport_registry["grpc"] = KeyManagementServiceGrpcTransport _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport - __all__ = ( "KeyManagementServiceTransport", "KeyManagementServiceGrpcTransport", diff --git a/google/cloud/kms_v1/services/key_management_service/transports/base.py b/google/cloud/kms_v1/services/key_management_service/transports/base.py index 43cfc0a5..2b246182 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/base.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/base.py @@ -23,7 +23,6 @@ from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.cloud.kms_v1.types import resources @@ -74,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. @@ -85,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: @@ -94,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 = { @@ -118,10 +117,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -133,10 +131,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -148,10 +145,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -163,10 +159,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -178,10 +173,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -193,10 +187,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -208,10 +201,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -223,10 +215,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -238,10 +229,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -253,10 +243,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -268,10 +257,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -293,10 +281,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -308,10 +295,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -323,10 +309,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -338,10 +323,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -353,10 +337,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -368,10 +351,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -383,10 +365,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -398,10 +379,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -413,10 +393,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, @@ -428,10 +407,9 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, - exceptions.InternalServerError, - exceptions.ServiceUnavailable, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), + deadline=60.0, ), default_timeout=60.0, client_info=client_info, diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py index 1992c5fa..4a001cc4 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -71,6 +71,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: @@ -101,12 +102,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: @@ -115,79 +120,70 @@ 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 - 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 - ) - - # 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 + self._ssl_channel_credentials = None - # 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, - ) 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 - ) + 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 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_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} # type: Dict[str, Callable] + else: + 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 + ) - # Run the base constructor. + # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, + scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, ) + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + @classmethod def create_channel( cls, @@ -200,7 +196,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optionsl[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 @@ -235,12 +231,8 @@ def create_channel( @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Return the channel from cache. return self._grpc_channel @property diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py index 57692915..330cfc7f 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -75,7 +75,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 @@ -115,6 +115,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: @@ -146,12 +147,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: @@ -160,78 +165,69 @@ 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 - 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" - ) + self._ssl_channel_credentials = None - 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, - ) else: - host = host if ":" in host else host + ":443" + 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 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_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) + else: + 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 + ) - # Run the base constructor. + # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, + scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, ) - self._stubs = {} + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # 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/kms_v1/types/__init__.py b/google/cloud/kms_v1/types/__init__.py index 5ef2bd36..35096a51 100644 --- a/google/cloud/kms_v1/types/__init__.py +++ b/google/cloud/kms_v1/types/__init__.py @@ -16,92 +16,93 @@ # from .resources import ( - KeyRing, CryptoKey, + CryptoKeyVersion, CryptoKeyVersionTemplate, + ExternalProtectionLevelOptions, + ImportJob, KeyOperationAttestation, - CryptoKeyVersion, + KeyRing, PublicKey, - ImportJob, - ExternalProtectionLevelOptions, + ProtectionLevel, ) from .service import ( - ListKeyRingsRequest, - ListCryptoKeysRequest, - ListCryptoKeyVersionsRequest, - ListImportJobsRequest, - ListKeyRingsResponse, - ListCryptoKeysResponse, - ListCryptoKeyVersionsResponse, - ListImportJobsResponse, - GetKeyRingRequest, - GetCryptoKeyRequest, - GetCryptoKeyVersionRequest, - GetPublicKeyRequest, - GetImportJobRequest, - CreateKeyRingRequest, + AsymmetricDecryptRequest, + AsymmetricDecryptResponse, + AsymmetricSignRequest, + AsymmetricSignResponse, CreateCryptoKeyRequest, CreateCryptoKeyVersionRequest, - ImportCryptoKeyVersionRequest, CreateImportJobRequest, - UpdateCryptoKeyRequest, - UpdateCryptoKeyVersionRequest, - EncryptRequest, + CreateKeyRingRequest, DecryptRequest, - AsymmetricSignRequest, - AsymmetricDecryptRequest, DecryptResponse, - EncryptResponse, - AsymmetricSignResponse, - AsymmetricDecryptResponse, - UpdateCryptoKeyPrimaryVersionRequest, DestroyCryptoKeyVersionRequest, - RestoreCryptoKeyVersionRequest, Digest, + EncryptRequest, + EncryptResponse, + GetCryptoKeyRequest, + GetCryptoKeyVersionRequest, + GetImportJobRequest, + GetKeyRingRequest, + GetPublicKeyRequest, + ImportCryptoKeyVersionRequest, + ListCryptoKeysRequest, + ListCryptoKeysResponse, + ListCryptoKeyVersionsRequest, + ListCryptoKeyVersionsResponse, + ListImportJobsRequest, + ListImportJobsResponse, + ListKeyRingsRequest, + ListKeyRingsResponse, LocationMetadata, + RestoreCryptoKeyVersionRequest, + UpdateCryptoKeyPrimaryVersionRequest, + UpdateCryptoKeyRequest, + UpdateCryptoKeyVersionRequest, ) - __all__ = ( - "KeyRing", "CryptoKey", + "CryptoKeyVersion", "CryptoKeyVersionTemplate", + "ExternalProtectionLevelOptions", + "ImportJob", "KeyOperationAttestation", - "CryptoKeyVersion", + "KeyRing", "PublicKey", - "ImportJob", - "ExternalProtectionLevelOptions", - "ListKeyRingsRequest", - "ListCryptoKeysRequest", - "ListCryptoKeyVersionsRequest", - "ListImportJobsRequest", - "ListKeyRingsResponse", - "ListCryptoKeysResponse", - "ListCryptoKeyVersionsResponse", - "ListImportJobsResponse", - "GetKeyRingRequest", - "GetCryptoKeyRequest", - "GetCryptoKeyVersionRequest", - "GetPublicKeyRequest", - "GetImportJobRequest", - "CreateKeyRingRequest", + "ProtectionLevel", + "AsymmetricDecryptRequest", + "AsymmetricDecryptResponse", + "AsymmetricSignRequest", + "AsymmetricSignResponse", "CreateCryptoKeyRequest", "CreateCryptoKeyVersionRequest", - "ImportCryptoKeyVersionRequest", "CreateImportJobRequest", - "UpdateCryptoKeyRequest", - "UpdateCryptoKeyVersionRequest", - "EncryptRequest", + "CreateKeyRingRequest", "DecryptRequest", - "AsymmetricSignRequest", - "AsymmetricDecryptRequest", "DecryptResponse", - "EncryptResponse", - "AsymmetricSignResponse", - "AsymmetricDecryptResponse", - "UpdateCryptoKeyPrimaryVersionRequest", "DestroyCryptoKeyVersionRequest", - "RestoreCryptoKeyVersionRequest", "Digest", + "EncryptRequest", + "EncryptResponse", + "GetCryptoKeyRequest", + "GetCryptoKeyVersionRequest", + "GetImportJobRequest", + "GetKeyRingRequest", + "GetPublicKeyRequest", + "ImportCryptoKeyVersionRequest", + "ListCryptoKeysRequest", + "ListCryptoKeysResponse", + "ListCryptoKeyVersionsRequest", + "ListCryptoKeyVersionsResponse", + "ListImportJobsRequest", + "ListImportJobsResponse", + "ListKeyRingsRequest", + "ListKeyRingsResponse", "LocationMetadata", + "RestoreCryptoKeyVersionRequest", + "UpdateCryptoKeyPrimaryVersionRequest", + "UpdateCryptoKeyRequest", + "UpdateCryptoKeyVersionRequest", ) diff --git a/google/cloud/kms_v1/types/resources.py b/google/cloud/kms_v1/types/resources.py index d984bc0a..27319980 100644 --- a/google/cloud/kms_v1/types/resources.py +++ b/google/cloud/kms_v1/types/resources.py @@ -60,7 +60,7 @@ class KeyRing(proto.Message): Output only. The resource name for the [KeyRing][google.cloud.kms.v1.KeyRing] in the format ``projects/*/locations/*/keyRings/*``. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time at which this [KeyRing][google.cloud.kms.v1.KeyRing] was created. """ @@ -83,7 +83,7 @@ class CryptoKey(proto.Message): Output only. The resource name for this [CryptoKey][google.cloud.kms.v1.CryptoKey] in the format ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - primary (~.resources.CryptoKeyVersion): + primary (google.cloud.kms_v1.types.CryptoKeyVersion): Output only. A copy of the "primary" [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that will be used by @@ -100,13 +100,13 @@ class CryptoKey(proto.Message): [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] may have a primary. For other keys, this field will be omitted. - purpose (~.resources.CryptoKey.CryptoKeyPurpose): + purpose (google.cloud.kms_v1.types.CryptoKey.CryptoKeyPurpose): Immutable. The immutable purpose of this [CryptoKey][google.cloud.kms.v1.CryptoKey]. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time at which this [CryptoKey][google.cloud.kms.v1.CryptoKey] was created. - next_rotation_time (~.timestamp.Timestamp): + next_rotation_time (google.protobuf.timestamp_pb2.Timestamp): At [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time], the Key Management Service will automatically: @@ -126,7 +126,7 @@ class CryptoKey(proto.Message): [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] support automatic rotation. For other keys, this field must be omitted. - rotation_period (~.duration.Duration): + rotation_period (google.protobuf.duration_pb2.Duration): [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] will be advanced by this period when the service automatically rotates a key. Must be at least 24 hours and @@ -142,7 +142,7 @@ class CryptoKey(proto.Message): [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] support automatic rotation. For other keys, this field must be omitted. - version_template (~.resources.CryptoKeyVersionTemplate): + version_template (google.cloud.kms_v1.types.CryptoKeyVersionTemplate): A template describing settings for new [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] instances. The properties of new @@ -150,7 +150,7 @@ class CryptoKey(proto.Message): instances created by either [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] or auto-rotation are controlled by this template. - labels (Sequence[~.resources.CryptoKey.LabelsEntry]): + labels (Sequence[google.cloud.kms_v1.types.CryptoKey.LabelsEntry]): Labels with user-defined metadata. For more information, see `Labeling Keys `__. @@ -202,13 +202,13 @@ class CryptoKeyVersionTemplate(proto.Message): or automatically as a result of auto-rotation. Attributes: - protection_level (~.resources.ProtectionLevel): + protection_level (google.cloud.kms_v1.types.ProtectionLevel): [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] to use when creating a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] based on this template. Immutable. Defaults to [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. - algorithm (~.resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): Required. [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] to use when creating a @@ -235,7 +235,7 @@ class KeyOperationAttestation(proto.Message): (https://cloud.google.com/kms/docs/attest-key). Attributes: - format (~.resources.KeyOperationAttestation.AttestationFormat): + format (google.cloud.kms_v1.types.KeyOperationAttestation.AttestationFormat): Output only. The format of the attestation data. content (bytes): @@ -275,42 +275,42 @@ class CryptoKeyVersion(proto.Message): [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the format ``projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*``. - state (~.resources.CryptoKeyVersion.CryptoKeyVersionState): + state (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionState): The current state of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - protection_level (~.resources.ProtectionLevel): + protection_level (google.cloud.kms_v1.types.ProtectionLevel): Output only. The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] describing how crypto operations are performed with this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - algorithm (~.resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): Output only. The [CryptoKeyVersionAlgorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] that this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] supports. - attestation (~.resources.KeyOperationAttestation): + attestation (google.cloud.kms_v1.types.KeyOperationAttestation): Output only. Statement that was generated and signed by the HSM at key creation time. Use this statement to verify attributes of the key as stored on the HSM, independently of Google. Only provided for key versions with [protection_level][google.cloud.kms.v1.CryptoKeyVersion.protection_level] [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time at which this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] was created. - generate_time (~.timestamp.Timestamp): + generate_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s key material was generated. - destroy_time (~.timestamp.Timestamp): + destroy_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s key material is scheduled for destruction. Only present if [state][google.cloud.kms.v1.CryptoKeyVersion.state] is [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED]. - destroy_event_time (~.timestamp.Timestamp): + destroy_event_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time this CryptoKeyVersion's key material was destroyed. Only present if [state][google.cloud.kms.v1.CryptoKeyVersion.state] is @@ -321,7 +321,7 @@ class CryptoKeyVersion(proto.Message): this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Only present if the underlying key material was imported. - import_time (~.timestamp.Timestamp): + import_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time at which this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s key material was imported. @@ -330,7 +330,7 @@ class CryptoKeyVersion(proto.Message): present if [state][google.cloud.kms.v1.CryptoKeyVersion.state] is [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED]. - external_protection_level_options (~.resources.ExternalProtectionLevelOptions): + external_protection_level_options (google.cloud.kms_v1.types.ExternalProtectionLevelOptions): ExternalProtectionLevelOptions stores a group of additional fields for configuring a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] @@ -433,7 +433,9 @@ class CryptoKeyVersionView(proto.Enum): algorithm = proto.Field(proto.ENUM, number=10, enum=CryptoKeyVersionAlgorithm,) - attestation = proto.Field(proto.MESSAGE, number=8, message=KeyOperationAttestation,) + attestation = proto.Field( + proto.MESSAGE, number=8, message="KeyOperationAttestation", + ) create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) @@ -470,11 +472,11 @@ class PublicKey(proto.Message): Considerations `__ and [Textual Encoding of Subject Public Key Info] (https://tools.ietf.org/html/rfc7468#section-13). - algorithm (~.resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): The [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] associated with this key. - pem_crc32c (~.wrappers.Int64Value): + pem_crc32c (google.protobuf.wrappers_pb2.Int64Value): Integrity verification field. A CRC32C checksum of the returned [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem]. An integrity check of @@ -503,7 +505,7 @@ class PublicKey(proto.Message): pem = proto.Field(proto.STRING, number=1) algorithm = proto.Field( - proto.ENUM, number=2, enum=CryptoKeyVersion.CryptoKeyVersionAlgorithm, + proto.ENUM, number=2, enum="CryptoKeyVersion.CryptoKeyVersionAlgorithm", ) pem_crc32c = proto.Field(proto.MESSAGE, number=3, message=wrappers.Int64Value,) @@ -553,10 +555,10 @@ class ImportJob(proto.Message): Output only. The resource name for this [ImportJob][google.cloud.kms.v1.ImportJob] in the format ``projects/*/locations/*/keyRings/*/importJobs/*``. - import_method (~.resources.ImportJob.ImportMethod): + import_method (google.cloud.kms_v1.types.ImportJob.ImportMethod): Required. Immutable. The wrapping method to be used for incoming key material. - protection_level (~.resources.ProtectionLevel): + protection_level (google.cloud.kms_v1.types.ProtectionLevel): Required. Immutable. The protection level of the [ImportJob][google.cloud.kms.v1.ImportJob]. This must match the @@ -565,32 +567,32 @@ class ImportJob(proto.Message): [version_template][google.cloud.kms.v1.CryptoKey.version_template] on the [CryptoKey][google.cloud.kms.v1.CryptoKey] you attempt to import into. - create_time (~.timestamp.Timestamp): + create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time at which this [ImportJob][google.cloud.kms.v1.ImportJob] was created. - generate_time (~.timestamp.Timestamp): + generate_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time this [ImportJob][google.cloud.kms.v1.ImportJob]'s key material was generated. - expire_time (~.timestamp.Timestamp): + expire_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time at which this [ImportJob][google.cloud.kms.v1.ImportJob] is scheduled for expiration and can no longer be used to import key material. - expire_event_time (~.timestamp.Timestamp): + expire_event_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time this [ImportJob][google.cloud.kms.v1.ImportJob] expired. Only present if [state][google.cloud.kms.v1.ImportJob.state] is [EXPIRED][google.cloud.kms.v1.ImportJob.ImportJobState.EXPIRED]. - state (~.resources.ImportJob.ImportJobState): + state (google.cloud.kms_v1.types.ImportJob.ImportJobState): Output only. The current state of the [ImportJob][google.cloud.kms.v1.ImportJob], indicating if it can be used. - public_key (~.resources.ImportJob.WrappingPublicKey): + public_key (google.cloud.kms_v1.types.ImportJob.WrappingPublicKey): Output only. The public key with which to wrap key material prior to import. Only returned if [state][google.cloud.kms.v1.ImportJob.state] is [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE]. - attestation (~.resources.KeyOperationAttestation): + attestation (google.cloud.kms_v1.types.KeyOperationAttestation): Output only. Statement that was generated and signed by the key creator (for example, an HSM) at key creation time. Use this statement to verify attributes of the key as stored on @@ -655,7 +657,9 @@ class WrappingPublicKey(proto.Message): public_key = proto.Field(proto.MESSAGE, number=7, message=WrappingPublicKey,) - attestation = proto.Field(proto.MESSAGE, number=8, message=KeyOperationAttestation,) + attestation = proto.Field( + proto.MESSAGE, number=8, message="KeyOperationAttestation", + ) class ExternalProtectionLevelOptions(proto.Message): diff --git a/google/cloud/kms_v1/types/service.py b/google/cloud/kms_v1/types/service.py index 7195dc00..6bd781bf 100644 --- a/google/cloud/kms_v1/types/service.py +++ b/google/cloud/kms_v1/types/service.py @@ -127,7 +127,7 @@ class ListCryptoKeysRequest(proto.Message): page_token (str): Optional. Optional pagination token, returned earlier via [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token]. - version_view (~.resources.CryptoKeyVersion.CryptoKeyVersionView): + version_view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): The fields of the primary version to include in the response. filter (str): @@ -178,7 +178,7 @@ class ListCryptoKeyVersionsRequest(proto.Message): page_token (str): Optional. Optional pagination token, returned earlier via [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token]. - view (~.resources.CryptoKeyVersion.CryptoKeyVersionView): + view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): The fields to include in the response. filter (str): Optional. Only include resources that match the filter in @@ -256,7 +256,7 @@ class ListKeyRingsResponse(proto.Message): [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. Attributes: - key_rings (Sequence[~.resources.KeyRing]): + key_rings (Sequence[google.cloud.kms_v1.types.KeyRing]): The list of [KeyRings][google.cloud.kms.v1.KeyRing]. next_page_token (str): A token to retrieve next page of results. Pass this value in @@ -283,7 +283,7 @@ class ListCryptoKeysResponse(proto.Message): [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. Attributes: - crypto_keys (Sequence[~.resources.CryptoKey]): + crypto_keys (Sequence[google.cloud.kms_v1.types.CryptoKey]): The list of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. next_page_token (str): A token to retrieve next page of results. Pass this value in @@ -313,7 +313,7 @@ class ListCryptoKeyVersionsResponse(proto.Message): [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. Attributes: - crypto_key_versions (Sequence[~.resources.CryptoKeyVersion]): + crypto_key_versions (Sequence[google.cloud.kms_v1.types.CryptoKeyVersion]): The list of [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. next_page_token (str): @@ -344,7 +344,7 @@ class ListImportJobsResponse(proto.Message): [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. Attributes: - import_jobs (Sequence[~.resources.ImportJob]): + import_jobs (Sequence[google.cloud.kms_v1.types.ImportJob]): The list of [ImportJobs][google.cloud.kms.v1.ImportJob]. next_page_token (str): A token to retrieve next page of results. Pass this value in @@ -450,7 +450,7 @@ class CreateKeyRingRequest(proto.Message): key_ring_id (str): Required. It must be unique within a location and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` - key_ring (~.resources.KeyRing): + key_ring (google.cloud.kms_v1.types.KeyRing): Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with initial field values. """ @@ -474,7 +474,7 @@ class CreateCryptoKeyRequest(proto.Message): crypto_key_id (str): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` - crypto_key (~.resources.CryptoKey): + crypto_key (google.cloud.kms_v1.types.CryptoKey): Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with initial field values. skip_initial_version_creation (bool): @@ -508,7 +508,7 @@ class CreateCryptoKeyVersionRequest(proto.Message): the [CryptoKey][google.cloud.kms.v1.CryptoKey] associated with the [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - crypto_key_version (~.resources.CryptoKeyVersion): + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): Required. A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with initial field values. @@ -530,7 +530,7 @@ class ImportCryptoKeyVersionRequest(proto.Message): Required. The [name][google.cloud.kms.v1.CryptoKey.name] of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to be imported into. - algorithm (~.resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): Required. The [algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] of the key being imported. This does not need to match the @@ -596,7 +596,7 @@ class CreateImportJobRequest(proto.Message): import_job_id (str): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` - import_job (~.resources.ImportJob): + import_job (google.cloud.kms_v1.types.ImportJob): Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with initial field values. """ @@ -613,10 +613,10 @@ class UpdateCryptoKeyRequest(proto.Message): [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. Attributes: - crypto_key (~.resources.CryptoKey): + crypto_key (google.cloud.kms_v1.types.CryptoKey): Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] with updated values. - update_mask (~.field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): Required. List of fields to be updated in this request. """ @@ -631,11 +631,11 @@ class UpdateCryptoKeyVersionRequest(proto.Message): [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. Attributes: - crypto_key_version (~.resources.CryptoKeyVersion): + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): Required. [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with updated values. - update_mask (~.field_mask.FieldMask): + update_mask (google.protobuf.field_mask_pb2.FieldMask): Required. List of fields to be updated in this request. """ @@ -685,7 +685,7 @@ class EncryptRequest(proto.Message): combined length of the plaintext and additional_authenticated_data fields must be no larger than 8KiB. - plaintext_crc32c (~.wrappers.Int64Value): + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. If specified, @@ -708,7 +708,7 @@ class EncryptRequest(proto.Message): languages that support this type. NOTE: This field is in Beta. - additional_authenticated_data_crc32c (~.wrappers.Int64Value): + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. If specified, @@ -764,7 +764,7 @@ class DecryptRequest(proto.Message): Optional. Optional data that must match the data originally supplied in [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. - ciphertext_crc32c (~.wrappers.Int64Value): + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. If specified, @@ -787,7 +787,7 @@ class DecryptRequest(proto.Message): languages that support this type. NOTE: This field is in Beta. - additional_authenticated_data_crc32c (~.wrappers.Int64Value): + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. If specified, @@ -836,12 +836,12 @@ class AsymmetricSignRequest(proto.Message): Required. The resource name of the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to use for signing. - digest (~.service.Digest): + digest (google.cloud.kms_v1.types.Digest): Required. The digest of the data to sign. The digest must be produced with the same digest algorithm as specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. - digest_crc32c (~.wrappers.Int64Value): + digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. If specified, @@ -886,7 +886,7 @@ class AsymmetricDecryptRequest(proto.Message): Required. The data encrypted with the named [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s public key using OAEP. - ciphertext_crc32c (~.wrappers.Int64Value): + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. If specified, @@ -928,7 +928,7 @@ class DecryptResponse(proto.Message): plaintext (bytes): The decrypted data originally supplied in [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. - plaintext_crc32c (~.wrappers.Int64Value): + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): Integrity verification field. A CRC32C checksum of the returned [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext]. @@ -973,7 +973,7 @@ class EncryptResponse(proto.Message): intended resource was used for encryption. ciphertext (bytes): The encrypted data. - ciphertext_crc32c (~.wrappers.Int64Value): + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): Integrity verification field. A CRC32C checksum of the returned [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. @@ -1048,7 +1048,7 @@ class AsymmetricSignResponse(proto.Message): Attributes: signature (bytes): The created signature. - signature_crc32c (~.wrappers.Int64Value): + signature_crc32c (google.protobuf.wrappers_pb2.Int64Value): Integrity verification field. A CRC32C checksum of the returned [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature]. @@ -1112,7 +1112,7 @@ class AsymmetricDecryptResponse(proto.Message): plaintext (bytes): The decrypted data originally encrypted with the matching public key. - plaintext_crc32c (~.wrappers.Int64Value): + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): Integrity verification field. A CRC32C checksum of the returned [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext]. diff --git a/noxfile.py b/noxfile.py index 4cec8f31..896d619a 100644 --- a/noxfile.py +++ b/noxfile.py @@ -18,6 +18,7 @@ from __future__ import absolute_import import os +import pathlib import shutil import nox @@ -28,7 +29,23 @@ DEFAULT_PYTHON_VERSION = "3.8" SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "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) @@ -70,18 +87,23 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. - session.install("asyncmock", "pytest-asyncio") - session.install("mock", "pytest", "pytest-cov") - session.install("-e", ".") + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + 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", - "--cov=google.cloud.cloudkms", - "--cov=google.cloud", - "--cov=tests.unit", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google/cloud", + "--cov=tests/unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", @@ -100,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") @@ -109,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) @@ -121,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) @@ -141,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=8") session.run("coverage", "erase") @@ -173,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/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/scripts/fixup_kms_v1_keywords.py b/scripts/fixup_kms_v1_keywords.py index 3d8255e2..00be642c 100644 --- a/scripts/fixup_kms_v1_keywords.py +++ b/scripts/fixup_kms_v1_keywords.py @@ -1,3 +1,4 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Google LLC diff --git a/setup.py b/setup.py index 67d2021a..26cc0c6f 100644 --- a/setup.py +++ b/setup.py @@ -27,10 +27,9 @@ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", "proto-plus >= 1.4.0", - "libcst >= 0.2.5", ] -extras = {} +extras = {"libcst": "libcst >= 0.2.5"} package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/synth.metadata b/synth.metadata index 0387636a..b2145772 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,22 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-kms.git", - "sha": "81db5d90112092772b83aec57e2358088ed88e0d" + "remote": "git@github.com:googleapis/python-kms", + "sha": "5723df440ca439d93a11deaae8d25ed945113803" + } + }, + { + "git": { + "name": "googleapis", + "remote": "https://github.com/googleapis/googleapis.git", + "sha": "915925089600094e72e4bfa8cf586c170e6b7109", + "internalRef": "366152684" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "dba48bb9bc6959c232bec9150ac6313b608fe7bd" + "sha": "6d76df2138f8f841e5a5b9ac427f81def520c15f" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "dba48bb9bc6959c232bec9150ac6313b608fe7bd" + "sha": "6d76df2138f8f841e5a5b9ac427f81def520c15f" } } ], diff --git a/synth.py b/synth.py index 6f66bc6c..3478e181 100644 --- a/synth.py +++ b/synth.py @@ -65,29 +65,18 @@ "\n\g<0>", ) -# TODO(busunkim): Remove once https://github.com/googleapis/gapic-generator-python/pull/555 is merged +# Rename `format_` to `format` to avoid breaking change s.replace( - "google/**/base.py", - """from google\.api_core import gapic_v1\s+# type: ignore""", - """from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore""", + "google/**/types/*.py", + "format_", + "format" ) -# fix bad indentation -s.replace( - "google/**/*service.py", - """(\s+)settings resource. -\s+If empty all mutable fields will be updated.""", - """\g<1>settings resource. -\g<1>If empty all mutable fields will be updated.""", -) - - # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- templated_files = common.py_library( - cov_level=99, + cov_level=98, samples=True, microgenerator=True, ) diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 23330fdd..6fce1954 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -8,4 +8,4 @@ google-api-core==1.22.2 grpc-google-iam-v1==0.12.3 proto-plus==1.4.0 -libcst==0.2.5 \ No newline at end of file +libcst==0.2.5 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index e69de29b..da93009b 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index e69de29b..da93009b 100644 --- a/testing/constraints-3.8.txt +++ b/testing/constraints-3.8.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index e69de29b..da93009b 100644 --- a/testing/constraints-3.9.txt +++ b/testing/constraints-3.9.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/tests/unit/gapic/kms_v1/__init__.py b/tests/unit/gapic/kms_v1/__init__.py index 8b137891..42ffdf2b 100644 --- a/tests/unit/gapic/kms_v1/__init__.py +++ b/tests/unit/gapic/kms_v1/__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/kms_v1/test_key_management_service.py b/tests/unit/gapic/kms_v1/test_key_management_service.py index f4598d4c..1cce2b8c 100644 --- a/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -98,7 +98,24 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize( - "client_class", [KeyManagementServiceClient, KeyManagementServiceAsyncClient] + "client_class", [KeyManagementServiceClient, KeyManagementServiceAsyncClient,] +) +def test_key_management_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 == "cloudkms.googleapis.com:443" + + +@pytest.mark.parametrize( + "client_class", [KeyManagementServiceClient, KeyManagementServiceAsyncClient,] ) def test_key_management_service_client_from_service_account_file(client_class): creds = credentials.AnonymousCredentials() @@ -107,17 +124,22 @@ def test_key_management_service_client_from_service_account_file(client_class): ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") - assert client._transport._credentials == creds + 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 client.transport._credentials == creds + assert isinstance(client, client_class) - assert client._transport._host == "cloudkms.googleapis.com:443" + assert client.transport._host == "cloudkms.googleapis.com:443" def test_key_management_service_client_get_transport_class(): transport = KeyManagementServiceClient.get_transport_class() - assert transport == transports.KeyManagementServiceGrpcTransport + available_transports = [ + transports.KeyManagementServiceGrpcTransport, + ] + assert transport in available_transports transport = KeyManagementServiceClient.get_transport_class("grpc") assert transport == transports.KeyManagementServiceGrpcTransport @@ -172,7 +194,7 @@ def test_key_management_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, ) @@ -188,7 +210,7 @@ def test_key_management_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, ) @@ -204,7 +226,7 @@ def test_key_management_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, ) @@ -232,7 +254,7 @@ def test_key_management_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, ) @@ -293,29 +315,25 @@ def test_key_management_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. @@ -324,66 +342,53 @@ def test_key_management_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", @@ -413,7 +418,7 @@ def test_key_management_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, ) @@ -447,7 +452,7 @@ def test_key_management_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, ) @@ -466,7 +471,7 @@ def test_key_management_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, ) @@ -484,7 +489,7 @@ def test_list_key_rings( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_key_rings), "__call__") as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListKeyRingsResponse( next_page_token="next_page_token_value", total_size=1086, @@ -499,6 +504,7 @@ def test_list_key_rings( assert args[0] == service.ListKeyRingsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyRingsPager) assert response.next_page_token == "next_page_token_value" @@ -510,20 +516,36 @@ def test_list_key_rings_from_dict(): test_list_key_rings(request_type=dict) +def test_list_key_rings_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 = KeyManagementServiceClient( + 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_key_rings), "__call__") as call: + client.list_key_rings() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListKeyRingsRequest() + + @pytest.mark.asyncio -async def test_list_key_rings_async(transport: str = "grpc_asyncio"): +async def test_list_key_rings_async( + transport: str = "grpc_asyncio", request_type=service.ListKeyRingsRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.ListKeyRingsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_key_rings), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListKeyRingsResponse( @@ -537,7 +559,7 @@ async def test_list_key_rings_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.ListKeyRingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListKeyRingsAsyncPager) @@ -547,6 +569,11 @@ async def test_list_key_rings_async(transport: str = "grpc_asyncio"): assert response.total_size == 1086 +@pytest.mark.asyncio +async def test_list_key_rings_async_from_dict(): + await test_list_key_rings_async(request_type=dict) + + def test_list_key_rings_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -556,7 +583,7 @@ def test_list_key_rings_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_key_rings), "__call__") as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: call.return_value = service.ListKeyRingsResponse() client.list_key_rings(request) @@ -583,9 +610,7 @@ async def test_list_key_rings_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_key_rings), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListKeyRingsResponse() ) @@ -606,7 +631,7 @@ def test_list_key_rings_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_key_rings), "__call__") as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListKeyRingsResponse() @@ -640,9 +665,7 @@ async def test_list_key_rings_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_key_rings), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListKeyRingsResponse() @@ -679,7 +702,7 @@ def test_list_key_rings_pager(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_key_rings), "__call__") as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListKeyRingsResponse( @@ -717,7 +740,7 @@ def test_list_key_rings_pages(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_key_rings), "__call__") as call: + with mock.patch.object(type(client.transport.list_key_rings), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListKeyRingsResponse( @@ -750,9 +773,7 @@ async def test_list_key_rings_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_key_rings), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_key_rings), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -791,9 +812,7 @@ async def test_list_key_rings_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_key_rings), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_key_rings), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -833,9 +852,7 @@ def test_list_crypto_keys( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListCryptoKeysResponse( next_page_token="next_page_token_value", total_size=1086, @@ -850,6 +867,7 @@ def test_list_crypto_keys( assert args[0] == service.ListCryptoKeysRequest() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeysPager) assert response.next_page_token == "next_page_token_value" @@ -861,20 +879,36 @@ def test_list_crypto_keys_from_dict(): test_list_crypto_keys(request_type=dict) +def test_list_crypto_keys_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 = KeyManagementServiceClient( + 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_crypto_keys), "__call__") as call: + client.list_crypto_keys() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListCryptoKeysRequest() + + @pytest.mark.asyncio -async def test_list_crypto_keys_async(transport: str = "grpc_asyncio"): +async def test_list_crypto_keys_async( + transport: str = "grpc_asyncio", request_type=service.ListCryptoKeysRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.ListCryptoKeysRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListCryptoKeysResponse( @@ -888,7 +922,7 @@ async def test_list_crypto_keys_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.ListCryptoKeysRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListCryptoKeysAsyncPager) @@ -898,6 +932,11 @@ async def test_list_crypto_keys_async(transport: str = "grpc_asyncio"): assert response.total_size == 1086 +@pytest.mark.asyncio +async def test_list_crypto_keys_async_from_dict(): + await test_list_crypto_keys_async(request_type=dict) + + def test_list_crypto_keys_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -907,9 +946,7 @@ def test_list_crypto_keys_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: call.return_value = service.ListCryptoKeysResponse() client.list_crypto_keys(request) @@ -936,9 +973,7 @@ async def test_list_crypto_keys_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListCryptoKeysResponse() ) @@ -959,9 +994,7 @@ def test_list_crypto_keys_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListCryptoKeysResponse() @@ -995,9 +1028,7 @@ async def test_list_crypto_keys_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListCryptoKeysResponse() @@ -1034,9 +1065,7 @@ def test_list_crypto_keys_pager(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListCryptoKeysResponse( @@ -1074,9 +1103,7 @@ def test_list_crypto_keys_pages(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_crypto_keys), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_crypto_keys), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListCryptoKeysResponse( @@ -1109,9 +1136,7 @@ async def test_list_crypto_keys_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_crypto_keys), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_crypto_keys), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1150,9 +1175,7 @@ async def test_list_crypto_keys_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_crypto_keys), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_crypto_keys), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1193,7 +1216,7 @@ def test_list_crypto_key_versions( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = service.ListCryptoKeyVersionsResponse( @@ -1209,6 +1232,7 @@ def test_list_crypto_key_versions( assert args[0] == service.ListCryptoKeyVersionsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeyVersionsPager) assert response.next_page_token == "next_page_token_value" @@ -1220,19 +1244,39 @@ def test_list_crypto_key_versions_from_dict(): test_list_crypto_key_versions(request_type=dict) +def test_list_crypto_key_versions_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 = KeyManagementServiceClient( + 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_crypto_key_versions), "__call__" + ) as call: + client.list_crypto_key_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListCryptoKeyVersionsRequest() + + @pytest.mark.asyncio -async def test_list_crypto_key_versions_async(transport: str = "grpc_asyncio"): +async def test_list_crypto_key_versions_async( + transport: str = "grpc_asyncio", request_type=service.ListCryptoKeyVersionsRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.ListCryptoKeyVersionsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -1247,7 +1291,7 @@ async def test_list_crypto_key_versions_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.ListCryptoKeyVersionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListCryptoKeyVersionsAsyncPager) @@ -1257,6 +1301,11 @@ async def test_list_crypto_key_versions_async(transport: str = "grpc_asyncio"): assert response.total_size == 1086 +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async_from_dict(): + await test_list_crypto_key_versions_async(request_type=dict) + + def test_list_crypto_key_versions_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1267,7 +1316,7 @@ def test_list_crypto_key_versions_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: call.return_value = service.ListCryptoKeyVersionsResponse() @@ -1296,7 +1345,7 @@ async def test_list_crypto_key_versions_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListCryptoKeyVersionsResponse() @@ -1319,7 +1368,7 @@ def test_list_crypto_key_versions_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = service.ListCryptoKeyVersionsResponse() @@ -1355,7 +1404,7 @@ async def test_list_crypto_key_versions_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = service.ListCryptoKeyVersionsResponse() @@ -1394,7 +1443,7 @@ def test_list_crypto_key_versions_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1440,7 +1489,7 @@ def test_list_crypto_key_versions_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.list_crypto_key_versions), "__call__" + type(client.transport.list_crypto_key_versions), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1480,7 +1529,7 @@ async def test_list_crypto_key_versions_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_crypto_key_versions), + type(client.transport.list_crypto_key_versions), "__call__", new_callable=mock.AsyncMock, ) as call: @@ -1527,7 +1576,7 @@ async def test_list_crypto_key_versions_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_crypto_key_versions), + type(client.transport.list_crypto_key_versions), "__call__", new_callable=mock.AsyncMock, ) as call: @@ -1575,9 +1624,7 @@ def test_list_import_jobs( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListImportJobsResponse( next_page_token="next_page_token_value", total_size=1086, @@ -1592,6 +1639,7 @@ def test_list_import_jobs( assert args[0] == service.ListImportJobsRequest() # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImportJobsPager) assert response.next_page_token == "next_page_token_value" @@ -1603,20 +1651,36 @@ def test_list_import_jobs_from_dict(): test_list_import_jobs(request_type=dict) +def test_list_import_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 = KeyManagementServiceClient( + 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_import_jobs), "__call__") as call: + client.list_import_jobs() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ListImportJobsRequest() + + @pytest.mark.asyncio -async def test_list_import_jobs_async(transport: str = "grpc_asyncio"): +async def test_list_import_jobs_async( + transport: str = "grpc_asyncio", request_type=service.ListImportJobsRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.ListImportJobsRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListImportJobsResponse( @@ -1630,7 +1694,7 @@ async def test_list_import_jobs_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.ListImportJobsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListImportJobsAsyncPager) @@ -1640,6 +1704,11 @@ async def test_list_import_jobs_async(transport: str = "grpc_asyncio"): assert response.total_size == 1086 +@pytest.mark.asyncio +async def test_list_import_jobs_async_from_dict(): + await test_list_import_jobs_async(request_type=dict) + + def test_list_import_jobs_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1649,9 +1718,7 @@ def test_list_import_jobs_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: call.return_value = service.ListImportJobsResponse() client.list_import_jobs(request) @@ -1678,9 +1745,7 @@ async def test_list_import_jobs_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.ListImportJobsResponse() ) @@ -1701,9 +1766,7 @@ def test_list_import_jobs_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListImportJobsResponse() @@ -1737,9 +1800,7 @@ async def test_list_import_jobs_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.ListImportJobsResponse() @@ -1776,9 +1837,7 @@ def test_list_import_jobs_pager(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListImportJobsResponse( @@ -1816,9 +1875,7 @@ def test_list_import_jobs_pages(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.list_import_jobs), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_import_jobs), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( service.ListImportJobsResponse( @@ -1851,9 +1908,7 @@ async def test_list_import_jobs_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_import_jobs), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_import_jobs), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1892,9 +1947,7 @@ async def test_list_import_jobs_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.list_import_jobs), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_import_jobs), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( @@ -1932,7 +1985,7 @@ def test_get_key_ring(transport: str = "grpc", request_type=service.GetKeyRingRe request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_key_ring), "__call__") as call: + with mock.patch.object(type(client.transport.get_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.KeyRing(name="name_value",) @@ -1945,6 +1998,7 @@ def test_get_key_ring(transport: str = "grpc", request_type=service.GetKeyRingRe assert args[0] == service.GetKeyRingRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) assert response.name == "name_value" @@ -1954,20 +2008,36 @@ def test_get_key_ring_from_dict(): test_get_key_ring(request_type=dict) +def test_get_key_ring_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 = KeyManagementServiceClient( + 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_key_ring), "__call__") as call: + client.get_key_ring() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetKeyRingRequest() + + @pytest.mark.asyncio -async def test_get_key_ring_async(transport: str = "grpc_asyncio"): +async def test_get_key_ring_async( + transport: str = "grpc_asyncio", request_type=service.GetKeyRingRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.GetKeyRingRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_key_ring), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.KeyRing(name="name_value",) @@ -1979,7 +2049,7 @@ async def test_get_key_ring_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.GetKeyRingRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.KeyRing) @@ -1987,6 +2057,11 @@ async def test_get_key_ring_async(transport: str = "grpc_asyncio"): assert response.name == "name_value" +@pytest.mark.asyncio +async def test_get_key_ring_async_from_dict(): + await test_get_key_ring_async(request_type=dict) + + def test_get_key_ring_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -1996,7 +2071,7 @@ def test_get_key_ring_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_key_ring), "__call__") as call: + with mock.patch.object(type(client.transport.get_key_ring), "__call__") as call: call.return_value = resources.KeyRing() client.get_key_ring(request) @@ -2023,9 +2098,7 @@ async def test_get_key_ring_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_key_ring), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_key_ring), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) await client.get_key_ring(request) @@ -2044,7 +2117,7 @@ def test_get_key_ring_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_key_ring), "__call__") as call: + with mock.patch.object(type(client.transport.get_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.KeyRing() @@ -2078,9 +2151,7 @@ async def test_get_key_ring_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_key_ring), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.KeyRing() @@ -2123,7 +2194,7 @@ def test_get_crypto_key( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_crypto_key), "__call__") as call: + with mock.patch.object(type(client.transport.get_crypto_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey( name="name_value", @@ -2140,6 +2211,7 @@ def test_get_crypto_key( assert args[0] == service.GetCryptoKeyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) assert response.name == "name_value" @@ -2151,20 +2223,36 @@ def test_get_crypto_key_from_dict(): test_get_crypto_key(request_type=dict) +def test_get_crypto_key_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 = KeyManagementServiceClient( + 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_crypto_key), "__call__") as call: + client.get_crypto_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetCryptoKeyRequest() + + @pytest.mark.asyncio -async def test_get_crypto_key_async(transport: str = "grpc_asyncio"): +async def test_get_crypto_key_async( + transport: str = "grpc_asyncio", request_type=service.GetCryptoKeyRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.GetCryptoKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_crypto_key), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_crypto_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKey( @@ -2179,7 +2267,7 @@ async def test_get_crypto_key_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.GetCryptoKeyRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKey) @@ -2189,6 +2277,11 @@ async def test_get_crypto_key_async(transport: str = "grpc_asyncio"): assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT +@pytest.mark.asyncio +async def test_get_crypto_key_async_from_dict(): + await test_get_crypto_key_async(request_type=dict) + + def test_get_crypto_key_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -2198,7 +2291,7 @@ def test_get_crypto_key_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_crypto_key), "__call__") as call: + with mock.patch.object(type(client.transport.get_crypto_key), "__call__") as call: call.return_value = resources.CryptoKey() client.get_crypto_key(request) @@ -2225,9 +2318,7 @@ async def test_get_crypto_key_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_crypto_key), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_crypto_key), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) await client.get_crypto_key(request) @@ -2246,7 +2337,7 @@ def test_get_crypto_key_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_crypto_key), "__call__") as call: + with mock.patch.object(type(client.transport.get_crypto_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -2280,9 +2371,7 @@ async def test_get_crypto_key_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_crypto_key), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_crypto_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -2326,7 +2415,7 @@ def test_get_crypto_key_version( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_crypto_key_version), "__call__" + type(client.transport.get_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion( @@ -2347,6 +2436,7 @@ def test_get_crypto_key_version( assert args[0] == service.GetCryptoKeyVersionRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" @@ -2372,19 +2462,39 @@ def test_get_crypto_key_version_from_dict(): test_get_crypto_key_version(request_type=dict) +def test_get_crypto_key_version_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 = KeyManagementServiceClient( + 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_crypto_key_version), "__call__" + ) as call: + client.get_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetCryptoKeyVersionRequest() + + @pytest.mark.asyncio -async def test_get_crypto_key_version_async(transport: str = "grpc_asyncio"): +async def test_get_crypto_key_version_async( + transport: str = "grpc_asyncio", request_type=service.GetCryptoKeyVersionRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.GetCryptoKeyVersionRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_crypto_key_version), "__call__" + type(client.transport.get_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -2404,7 +2514,7 @@ async def test_get_crypto_key_version_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.GetCryptoKeyVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKeyVersion) @@ -2428,6 +2538,11 @@ async def test_get_crypto_key_version_async(transport: str = "grpc_asyncio"): assert response.import_failure_reason == "import_failure_reason_value" +@pytest.mark.asyncio +async def test_get_crypto_key_version_async_from_dict(): + await test_get_crypto_key_version_async(request_type=dict) + + def test_get_crypto_key_version_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -2438,7 +2553,7 @@ def test_get_crypto_key_version_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_crypto_key_version), "__call__" + type(client.transport.get_crypto_key_version), "__call__" ) as call: call.return_value = resources.CryptoKeyVersion() @@ -2467,7 +2582,7 @@ async def test_get_crypto_key_version_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_crypto_key_version), "__call__" + type(client.transport.get_crypto_key_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKeyVersion() @@ -2490,7 +2605,7 @@ def test_get_crypto_key_version_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.get_crypto_key_version), "__call__" + type(client.transport.get_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -2526,7 +2641,7 @@ async def test_get_crypto_key_version_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.get_crypto_key_version), "__call__" + type(client.transport.get_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -2572,7 +2687,7 @@ def test_get_public_key( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_public_key), "__call__") as call: + with mock.patch.object(type(client.transport.get_public_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.PublicKey( pem="pem_value", @@ -2589,6 +2704,7 @@ def test_get_public_key( assert args[0] == service.GetPublicKeyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.PublicKey) assert response.pem == "pem_value" @@ -2605,20 +2721,36 @@ def test_get_public_key_from_dict(): test_get_public_key(request_type=dict) -@pytest.mark.asyncio -async def test_get_public_key_async(transport: str = "grpc_asyncio"): - client = KeyManagementServiceAsyncClient( +def test_get_public_key_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 = KeyManagementServiceClient( + 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_public_key), "__call__") as call: + client.get_public_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetPublicKeyRequest() + + +@pytest.mark.asyncio +async def test_get_public_key_async( + transport: str = "grpc_asyncio", request_type=service.GetPublicKeyRequest +): + client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.GetPublicKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_public_key), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_public_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.PublicKey( @@ -2634,7 +2766,7 @@ async def test_get_public_key_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.GetPublicKeyRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.PublicKey) @@ -2649,6 +2781,11 @@ async def test_get_public_key_async(transport: str = "grpc_asyncio"): assert response.name == "name_value" +@pytest.mark.asyncio +async def test_get_public_key_async_from_dict(): + await test_get_public_key_async(request_type=dict) + + def test_get_public_key_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -2658,7 +2795,7 @@ def test_get_public_key_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_public_key), "__call__") as call: + with mock.patch.object(type(client.transport.get_public_key), "__call__") as call: call.return_value = resources.PublicKey() client.get_public_key(request) @@ -2685,9 +2822,7 @@ async def test_get_public_key_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_public_key), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_public_key), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) await client.get_public_key(request) @@ -2706,7 +2841,7 @@ def test_get_public_key_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_public_key), "__call__") as call: + with mock.patch.object(type(client.transport.get_public_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.PublicKey() @@ -2740,9 +2875,7 @@ async def test_get_public_key_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_public_key), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_public_key), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.PublicKey() @@ -2785,7 +2918,7 @@ def test_get_import_job( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_import_job), "__call__") as call: + with mock.patch.object(type(client.transport.get_import_job), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.ImportJob( name="name_value", @@ -2803,6 +2936,7 @@ def test_get_import_job( assert args[0] == service.GetImportJobRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) assert response.name == "name_value" @@ -2821,20 +2955,36 @@ def test_get_import_job_from_dict(): test_get_import_job(request_type=dict) +def test_get_import_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 = KeyManagementServiceClient( + 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_import_job), "__call__") as call: + client.get_import_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.GetImportJobRequest() + + @pytest.mark.asyncio -async def test_get_import_job_async(transport: str = "grpc_asyncio"): +async def test_get_import_job_async( + transport: str = "grpc_asyncio", request_type=service.GetImportJobRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.GetImportJobRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_import_job), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_import_job), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.ImportJob( @@ -2851,7 +3001,7 @@ async def test_get_import_job_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.GetImportJobRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.ImportJob) @@ -2868,6 +3018,11 @@ async def test_get_import_job_async(transport: str = "grpc_asyncio"): assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION +@pytest.mark.asyncio +async def test_get_import_job_async_from_dict(): + await test_get_import_job_async(request_type=dict) + + def test_get_import_job_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -2877,7 +3032,7 @@ def test_get_import_job_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_import_job), "__call__") as call: + with mock.patch.object(type(client.transport.get_import_job), "__call__") as call: call.return_value = resources.ImportJob() client.get_import_job(request) @@ -2904,9 +3059,7 @@ async def test_get_import_job_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_import_job), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_import_job), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) await client.get_import_job(request) @@ -2925,7 +3078,7 @@ def test_get_import_job_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_import_job), "__call__") as call: + with mock.patch.object(type(client.transport.get_import_job), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.ImportJob() @@ -2959,9 +3112,7 @@ async def test_get_import_job_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_import_job), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_import_job), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.ImportJob() @@ -3004,7 +3155,7 @@ def test_create_key_ring( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_key_ring), "__call__") as call: + with mock.patch.object(type(client.transport.create_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.KeyRing(name="name_value",) @@ -3017,6 +3168,7 @@ def test_create_key_ring( assert args[0] == service.CreateKeyRingRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) assert response.name == "name_value" @@ -3026,20 +3178,36 @@ def test_create_key_ring_from_dict(): test_create_key_ring(request_type=dict) +def test_create_key_ring_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 = KeyManagementServiceClient( + 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_key_ring), "__call__") as call: + client.create_key_ring() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.CreateKeyRingRequest() + + @pytest.mark.asyncio -async def test_create_key_ring_async(transport: str = "grpc_asyncio"): +async def test_create_key_ring_async( + transport: str = "grpc_asyncio", request_type=service.CreateKeyRingRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.CreateKeyRingRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_key_ring), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.KeyRing(name="name_value",) @@ -3051,7 +3219,7 @@ async def test_create_key_ring_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.CreateKeyRingRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.KeyRing) @@ -3059,6 +3227,11 @@ async def test_create_key_ring_async(transport: str = "grpc_asyncio"): assert response.name == "name_value" +@pytest.mark.asyncio +async def test_create_key_ring_async_from_dict(): + await test_create_key_ring_async(request_type=dict) + + def test_create_key_ring_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -3068,7 +3241,7 @@ def test_create_key_ring_field_headers(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_key_ring), "__call__") as call: + with mock.patch.object(type(client.transport.create_key_ring), "__call__") as call: call.return_value = resources.KeyRing() client.create_key_ring(request) @@ -3095,9 +3268,7 @@ async def test_create_key_ring_field_headers_async(): request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_key_ring), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_ring), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) await client.create_key_ring(request) @@ -3116,7 +3287,7 @@ def test_create_key_ring_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_key_ring), "__call__") as call: + with mock.patch.object(type(client.transport.create_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.KeyRing() @@ -3161,9 +3332,7 @@ async def test_create_key_ring_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.create_key_ring), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_ring), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.KeyRing() @@ -3218,7 +3387,7 @@ def test_create_crypto_key( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_crypto_key), "__call__" + type(client.transport.create_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey( @@ -3236,6 +3405,7 @@ def test_create_crypto_key( assert args[0] == service.CreateCryptoKeyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) assert response.name == "name_value" @@ -3247,19 +3417,39 @@ def test_create_crypto_key_from_dict(): test_create_crypto_key(request_type=dict) +def test_create_crypto_key_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 = KeyManagementServiceClient( + 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_crypto_key), "__call__" + ) as call: + client.create_crypto_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.CreateCryptoKeyRequest() + + @pytest.mark.asyncio -async def test_create_crypto_key_async(transport: str = "grpc_asyncio"): +async def test_create_crypto_key_async( + transport: str = "grpc_asyncio", request_type=service.CreateCryptoKeyRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.CreateCryptoKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_crypto_key), "__call__" + type(client.transport.create_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -3275,7 +3465,7 @@ async def test_create_crypto_key_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.CreateCryptoKeyRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKey) @@ -3285,6 +3475,11 @@ async def test_create_crypto_key_async(transport: str = "grpc_asyncio"): assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT +@pytest.mark.asyncio +async def test_create_crypto_key_async_from_dict(): + await test_create_crypto_key_async(request_type=dict) + + def test_create_crypto_key_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -3295,7 +3490,7 @@ def test_create_crypto_key_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_crypto_key), "__call__" + type(client.transport.create_crypto_key), "__call__" ) as call: call.return_value = resources.CryptoKey() @@ -3324,7 +3519,7 @@ async def test_create_crypto_key_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_crypto_key), "__call__" + type(client.transport.create_crypto_key), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) @@ -3345,7 +3540,7 @@ def test_create_crypto_key_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_crypto_key), "__call__" + type(client.transport.create_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -3392,7 +3587,7 @@ async def test_create_crypto_key_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_crypto_key), "__call__" + type(client.transport.create_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -3448,7 +3643,7 @@ def test_create_crypto_key_version( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_crypto_key_version), "__call__" + type(client.transport.create_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion( @@ -3469,6 +3664,7 @@ def test_create_crypto_key_version( assert args[0] == service.CreateCryptoKeyVersionRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" @@ -3494,19 +3690,39 @@ def test_create_crypto_key_version_from_dict(): test_create_crypto_key_version(request_type=dict) +def test_create_crypto_key_version_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 = KeyManagementServiceClient( + 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_crypto_key_version), "__call__" + ) as call: + client.create_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.CreateCryptoKeyVersionRequest() + + @pytest.mark.asyncio -async def test_create_crypto_key_version_async(transport: str = "grpc_asyncio"): +async def test_create_crypto_key_version_async( + transport: str = "grpc_asyncio", request_type=service.CreateCryptoKeyVersionRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.CreateCryptoKeyVersionRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_crypto_key_version), "__call__" + type(client.transport.create_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -3526,7 +3742,7 @@ async def test_create_crypto_key_version_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.CreateCryptoKeyVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKeyVersion) @@ -3550,6 +3766,11 @@ async def test_create_crypto_key_version_async(transport: str = "grpc_asyncio"): assert response.import_failure_reason == "import_failure_reason_value" +@pytest.mark.asyncio +async def test_create_crypto_key_version_async_from_dict(): + await test_create_crypto_key_version_async(request_type=dict) + + def test_create_crypto_key_version_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -3560,7 +3781,7 @@ def test_create_crypto_key_version_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_crypto_key_version), "__call__" + type(client.transport.create_crypto_key_version), "__call__" ) as call: call.return_value = resources.CryptoKeyVersion() @@ -3589,7 +3810,7 @@ async def test_create_crypto_key_version_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_crypto_key_version), "__call__" + type(client.transport.create_crypto_key_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKeyVersion() @@ -3612,7 +3833,7 @@ def test_create_crypto_key_version_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_crypto_key_version), "__call__" + type(client.transport.create_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -3657,7 +3878,7 @@ async def test_create_crypto_key_version_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_crypto_key_version), "__call__" + type(client.transport.create_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -3713,7 +3934,7 @@ def test_import_crypto_key_version( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.import_crypto_key_version), "__call__" + type(client.transport.import_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion( @@ -3734,6 +3955,7 @@ def test_import_crypto_key_version( assert args[0] == service.ImportCryptoKeyVersionRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" @@ -3759,19 +3981,39 @@ def test_import_crypto_key_version_from_dict(): test_import_crypto_key_version(request_type=dict) +def test_import_crypto_key_version_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 = KeyManagementServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), "__call__" + ) as call: + client.import_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.ImportCryptoKeyVersionRequest() + + @pytest.mark.asyncio -async def test_import_crypto_key_version_async(transport: str = "grpc_asyncio"): +async def test_import_crypto_key_version_async( + transport: str = "grpc_asyncio", request_type=service.ImportCryptoKeyVersionRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.ImportCryptoKeyVersionRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.import_crypto_key_version), "__call__" + type(client.transport.import_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -3791,7 +4033,7 @@ async def test_import_crypto_key_version_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.ImportCryptoKeyVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKeyVersion) @@ -3815,6 +4057,11 @@ async def test_import_crypto_key_version_async(transport: str = "grpc_asyncio"): assert response.import_failure_reason == "import_failure_reason_value" +@pytest.mark.asyncio +async def test_import_crypto_key_version_async_from_dict(): + await test_import_crypto_key_version_async(request_type=dict) + + def test_import_crypto_key_version_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -3825,7 +4072,7 @@ def test_import_crypto_key_version_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.import_crypto_key_version), "__call__" + type(client.transport.import_crypto_key_version), "__call__" ) as call: call.return_value = resources.CryptoKeyVersion() @@ -3854,7 +4101,7 @@ async def test_import_crypto_key_version_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.import_crypto_key_version), "__call__" + type(client.transport.import_crypto_key_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKeyVersion() @@ -3885,7 +4132,7 @@ def test_create_import_job( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_import_job), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.ImportJob( @@ -3904,6 +4151,7 @@ def test_create_import_job( assert args[0] == service.CreateImportJobRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) assert response.name == "name_value" @@ -3922,19 +4170,39 @@ def test_create_import_job_from_dict(): test_create_import_job(request_type=dict) +def test_create_import_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 = KeyManagementServiceClient( + 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_import_job), "__call__" + ) as call: + client.create_import_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.CreateImportJobRequest() + + @pytest.mark.asyncio -async def test_create_import_job_async(transport: str = "grpc_asyncio"): +async def test_create_import_job_async( + transport: str = "grpc_asyncio", request_type=service.CreateImportJobRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.CreateImportJobRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_import_job), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -3952,7 +4220,7 @@ async def test_create_import_job_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.CreateImportJobRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.ImportJob) @@ -3969,6 +4237,11 @@ async def test_create_import_job_async(transport: str = "grpc_asyncio"): assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION +@pytest.mark.asyncio +async def test_create_import_job_async_from_dict(): + await test_create_import_job_async(request_type=dict) + + def test_create_import_job_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -3979,7 +4252,7 @@ def test_create_import_job_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_import_job), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: call.return_value = resources.ImportJob() @@ -4008,7 +4281,7 @@ async def test_create_import_job_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_import_job), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) @@ -4029,7 +4302,7 @@ def test_create_import_job_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.create_import_job), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.ImportJob() @@ -4076,7 +4349,7 @@ async def test_create_import_job_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.create_import_job), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.ImportJob() @@ -4132,7 +4405,7 @@ def test_update_crypto_key( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey( @@ -4150,6 +4423,7 @@ def test_update_crypto_key( assert args[0] == service.UpdateCryptoKeyRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) assert response.name == "name_value" @@ -4161,19 +4435,39 @@ def test_update_crypto_key_from_dict(): test_update_crypto_key(request_type=dict) +def test_update_crypto_key_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 = KeyManagementServiceClient( + 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_crypto_key), "__call__" + ) as call: + client.update_crypto_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.UpdateCryptoKeyRequest() + + @pytest.mark.asyncio -async def test_update_crypto_key_async(transport: str = "grpc_asyncio"): +async def test_update_crypto_key_async( + transport: str = "grpc_asyncio", request_type=service.UpdateCryptoKeyRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.UpdateCryptoKeyRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -4189,7 +4483,7 @@ async def test_update_crypto_key_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.UpdateCryptoKeyRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKey) @@ -4199,6 +4493,11 @@ async def test_update_crypto_key_async(transport: str = "grpc_asyncio"): assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT +@pytest.mark.asyncio +async def test_update_crypto_key_async_from_dict(): + await test_update_crypto_key_async(request_type=dict) + + def test_update_crypto_key_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -4209,7 +4508,7 @@ def test_update_crypto_key_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: call.return_value = resources.CryptoKey() @@ -4240,7 +4539,7 @@ async def test_update_crypto_key_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) @@ -4263,7 +4562,7 @@ def test_update_crypto_key_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -4306,7 +4605,7 @@ async def test_update_crypto_key_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -4358,7 +4657,7 @@ def test_update_crypto_key_version( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion( @@ -4379,6 +4678,7 @@ def test_update_crypto_key_version( assert args[0] == service.UpdateCryptoKeyVersionRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" @@ -4404,19 +4704,39 @@ def test_update_crypto_key_version_from_dict(): test_update_crypto_key_version(request_type=dict) +def test_update_crypto_key_version_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 = KeyManagementServiceClient( + 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_crypto_key_version), "__call__" + ) as call: + client.update_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.UpdateCryptoKeyVersionRequest() + + @pytest.mark.asyncio -async def test_update_crypto_key_version_async(transport: str = "grpc_asyncio"): +async def test_update_crypto_key_version_async( + transport: str = "grpc_asyncio", request_type=service.UpdateCryptoKeyVersionRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.UpdateCryptoKeyVersionRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -4436,7 +4756,7 @@ async def test_update_crypto_key_version_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.UpdateCryptoKeyVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKeyVersion) @@ -4460,6 +4780,11 @@ async def test_update_crypto_key_version_async(transport: str = "grpc_asyncio"): assert response.import_failure_reason == "import_failure_reason_value" +@pytest.mark.asyncio +async def test_update_crypto_key_version_async_from_dict(): + await test_update_crypto_key_version_async(request_type=dict) + + def test_update_crypto_key_version_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -4470,7 +4795,7 @@ def test_update_crypto_key_version_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: call.return_value = resources.CryptoKeyVersion() @@ -4502,7 +4827,7 @@ async def test_update_crypto_key_version_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKeyVersion() @@ -4528,7 +4853,7 @@ def test_update_crypto_key_version_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -4573,7 +4898,7 @@ async def test_update_crypto_key_version_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -4626,7 +4951,7 @@ def test_encrypt(transport: str = "grpc", request_type=service.EncryptRequest): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.EncryptResponse( name="name_value", @@ -4644,6 +4969,7 @@ def test_encrypt(transport: str = "grpc", request_type=service.EncryptRequest): assert args[0] == service.EncryptRequest() # Establish that the response is the type that we expect. + assert isinstance(response, service.EncryptResponse) assert response.name == "name_value" @@ -4659,18 +4985,36 @@ def test_encrypt_from_dict(): test_encrypt(request_type=dict) +def test_encrypt_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 = KeyManagementServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + client.encrypt() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.EncryptRequest() + + @pytest.mark.asyncio -async def test_encrypt_async(transport: str = "grpc_asyncio"): +async def test_encrypt_async( + transport: str = "grpc_asyncio", request_type=service.EncryptRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.EncryptRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.EncryptResponse( @@ -4687,7 +5031,7 @@ async def test_encrypt_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.EncryptRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.EncryptResponse) @@ -4701,6 +5045,11 @@ async def test_encrypt_async(transport: str = "grpc_asyncio"): assert response.verified_additional_authenticated_data_crc32c is True +@pytest.mark.asyncio +async def test_encrypt_async_from_dict(): + await test_encrypt_async(request_type=dict) + + def test_encrypt_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -4710,7 +5059,7 @@ def test_encrypt_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: call.return_value = service.EncryptResponse() client.encrypt(request) @@ -4737,7 +5086,7 @@ async def test_encrypt_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.EncryptResponse() ) @@ -4758,7 +5107,7 @@ def test_encrypt_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.EncryptResponse() @@ -4796,7 +5145,7 @@ async def test_encrypt_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.EncryptResponse() @@ -4841,7 +5190,7 @@ def test_decrypt(transport: str = "grpc", request_type=service.DecryptRequest): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.DecryptResponse(plaintext=b"plaintext_blob",) @@ -4854,6 +5203,7 @@ def test_decrypt(transport: str = "grpc", request_type=service.DecryptRequest): assert args[0] == service.DecryptRequest() # Establish that the response is the type that we expect. + assert isinstance(response, service.DecryptResponse) assert response.plaintext == b"plaintext_blob" @@ -4863,18 +5213,36 @@ def test_decrypt_from_dict(): test_decrypt(request_type=dict) +def test_decrypt_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 = KeyManagementServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + client.decrypt() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DecryptRequest() + + @pytest.mark.asyncio -async def test_decrypt_async(transport: str = "grpc_asyncio"): +async def test_decrypt_async( + transport: str = "grpc_asyncio", request_type=service.DecryptRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.DecryptRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.DecryptResponse(plaintext=b"plaintext_blob",) @@ -4886,7 +5254,7 @@ async def test_decrypt_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.DecryptRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.DecryptResponse) @@ -4894,6 +5262,11 @@ async def test_decrypt_async(transport: str = "grpc_asyncio"): assert response.plaintext == b"plaintext_blob" +@pytest.mark.asyncio +async def test_decrypt_async_from_dict(): + await test_decrypt_async(request_type=dict) + + def test_decrypt_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -4903,7 +5276,7 @@ def test_decrypt_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: call.return_value = service.DecryptResponse() client.decrypt(request) @@ -4930,7 +5303,7 @@ async def test_decrypt_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.DecryptResponse() ) @@ -4951,7 +5324,7 @@ def test_decrypt_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.DecryptResponse() @@ -4989,7 +5362,7 @@ async def test_decrypt_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._client._transport.decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.DecryptResponse() @@ -5038,7 +5411,7 @@ def test_asymmetric_sign( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.AsymmetricSignResponse( signature=b"signature_blob", verified_digest_crc32c=True, name="name_value", @@ -5053,6 +5426,7 @@ def test_asymmetric_sign( assert args[0] == service.AsymmetricSignRequest() # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) assert response.signature == b"signature_blob" @@ -5066,20 +5440,36 @@ def test_asymmetric_sign_from_dict(): test_asymmetric_sign(request_type=dict) +def test_asymmetric_sign_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 = KeyManagementServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: + client.asymmetric_sign() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.AsymmetricSignRequest() + + @pytest.mark.asyncio -async def test_asymmetric_sign_async(transport: str = "grpc_asyncio"): +async def test_asymmetric_sign_async( + transport: str = "grpc_asyncio", request_type=service.AsymmetricSignRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.AsymmetricSignRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.asymmetric_sign), "__call__" - ) as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.AsymmetricSignResponse( @@ -5095,7 +5485,7 @@ async def test_asymmetric_sign_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.AsymmetricSignRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.AsymmetricSignResponse) @@ -5107,6 +5497,11 @@ async def test_asymmetric_sign_async(transport: str = "grpc_asyncio"): assert response.name == "name_value" +@pytest.mark.asyncio +async def test_asymmetric_sign_async_from_dict(): + await test_asymmetric_sign_async(request_type=dict) + + def test_asymmetric_sign_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -5116,7 +5511,7 @@ def test_asymmetric_sign_field_headers(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: call.return_value = service.AsymmetricSignResponse() client.asymmetric_sign(request) @@ -5143,9 +5538,7 @@ async def test_asymmetric_sign_field_headers_async(): request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.asymmetric_sign), "__call__" - ) as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.AsymmetricSignResponse() ) @@ -5166,7 +5559,7 @@ def test_asymmetric_sign_flattened(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.AsymmetricSignResponse() @@ -5206,9 +5599,7 @@ async def test_asymmetric_sign_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.asymmetric_sign), "__call__" - ) as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = service.AsymmetricSignResponse() @@ -5260,7 +5651,7 @@ def test_asymmetric_decrypt( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.asymmetric_decrypt), "__call__" + type(client.transport.asymmetric_decrypt), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = service.AsymmetricDecryptResponse( @@ -5276,6 +5667,7 @@ def test_asymmetric_decrypt( assert args[0] == service.AsymmetricDecryptRequest() # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricDecryptResponse) assert response.plaintext == b"plaintext_blob" @@ -5287,19 +5679,39 @@ def test_asymmetric_decrypt_from_dict(): test_asymmetric_decrypt(request_type=dict) +def test_asymmetric_decrypt_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 = KeyManagementServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: + client.asymmetric_decrypt() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.AsymmetricDecryptRequest() + + @pytest.mark.asyncio -async def test_asymmetric_decrypt_async(transport: str = "grpc_asyncio"): +async def test_asymmetric_decrypt_async( + transport: str = "grpc_asyncio", request_type=service.AsymmetricDecryptRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.AsymmetricDecryptRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.asymmetric_decrypt), "__call__" + type(client.transport.asymmetric_decrypt), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -5314,7 +5726,7 @@ async def test_asymmetric_decrypt_async(transport: str = "grpc_asyncio"): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.AsymmetricDecryptRequest() # Establish that the response is the type that we expect. assert isinstance(response, service.AsymmetricDecryptResponse) @@ -5324,6 +5736,11 @@ async def test_asymmetric_decrypt_async(transport: str = "grpc_asyncio"): assert response.verified_ciphertext_crc32c is True +@pytest.mark.asyncio +async def test_asymmetric_decrypt_async_from_dict(): + await test_asymmetric_decrypt_async(request_type=dict) + + def test_asymmetric_decrypt_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -5334,7 +5751,7 @@ def test_asymmetric_decrypt_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.asymmetric_decrypt), "__call__" + type(client.transport.asymmetric_decrypt), "__call__" ) as call: call.return_value = service.AsymmetricDecryptResponse() @@ -5363,7 +5780,7 @@ async def test_asymmetric_decrypt_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.asymmetric_decrypt), "__call__" + type(client.transport.asymmetric_decrypt), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( service.AsymmetricDecryptResponse() @@ -5386,7 +5803,7 @@ def test_asymmetric_decrypt_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.asymmetric_decrypt), "__call__" + type(client.transport.asymmetric_decrypt), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = service.AsymmetricDecryptResponse() @@ -5428,7 +5845,7 @@ async def test_asymmetric_decrypt_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.asymmetric_decrypt), "__call__" + type(client.transport.asymmetric_decrypt), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = service.AsymmetricDecryptResponse() @@ -5481,7 +5898,7 @@ def test_update_crypto_key_primary_version( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey( @@ -5499,6 +5916,7 @@ def test_update_crypto_key_primary_version( assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) assert response.name == "name_value" @@ -5510,19 +5928,40 @@ def test_update_crypto_key_primary_version_from_dict(): test_update_crypto_key_primary_version(request_type=dict) +def test_update_crypto_key_primary_version_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 = KeyManagementServiceClient( + 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_crypto_key_primary_version), "__call__" + ) as call: + client.update_crypto_key_primary_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() + + @pytest.mark.asyncio -async def test_update_crypto_key_primary_version_async(transport: str = "grpc_asyncio"): +async def test_update_crypto_key_primary_version_async( + transport: str = "grpc_asyncio", + request_type=service.UpdateCryptoKeyPrimaryVersionRequest, +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.UpdateCryptoKeyPrimaryVersionRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -5538,7 +5977,7 @@ async def test_update_crypto_key_primary_version_async(transport: str = "grpc_as assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKey) @@ -5548,6 +5987,11 @@ async def test_update_crypto_key_primary_version_async(transport: str = "grpc_as assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_async_from_dict(): + await test_update_crypto_key_primary_version_async(request_type=dict) + + def test_update_crypto_key_primary_version_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -5558,7 +6002,7 @@ def test_update_crypto_key_primary_version_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: call.return_value = resources.CryptoKey() @@ -5587,7 +6031,7 @@ async def test_update_crypto_key_primary_version_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) @@ -5608,7 +6052,7 @@ def test_update_crypto_key_primary_version_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -5650,7 +6094,7 @@ async def test_update_crypto_key_primary_version_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -5701,7 +6145,7 @@ def test_destroy_crypto_key_version( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.destroy_crypto_key_version), "__call__" + type(client.transport.destroy_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion( @@ -5722,6 +6166,7 @@ def test_destroy_crypto_key_version( assert args[0] == service.DestroyCryptoKeyVersionRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" @@ -5747,19 +6192,39 @@ def test_destroy_crypto_key_version_from_dict(): test_destroy_crypto_key_version(request_type=dict) +def test_destroy_crypto_key_version_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 = KeyManagementServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: + client.destroy_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.DestroyCryptoKeyVersionRequest() + + @pytest.mark.asyncio -async def test_destroy_crypto_key_version_async(transport: str = "grpc_asyncio"): +async def test_destroy_crypto_key_version_async( + transport: str = "grpc_asyncio", request_type=service.DestroyCryptoKeyVersionRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.DestroyCryptoKeyVersionRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.destroy_crypto_key_version), "__call__" + type(client.transport.destroy_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -5779,7 +6244,7 @@ async def test_destroy_crypto_key_version_async(transport: str = "grpc_asyncio") assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.DestroyCryptoKeyVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKeyVersion) @@ -5803,6 +6268,11 @@ async def test_destroy_crypto_key_version_async(transport: str = "grpc_asyncio") assert response.import_failure_reason == "import_failure_reason_value" +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_async_from_dict(): + await test_destroy_crypto_key_version_async(request_type=dict) + + def test_destroy_crypto_key_version_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -5813,7 +6283,7 @@ def test_destroy_crypto_key_version_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.destroy_crypto_key_version), "__call__" + type(client.transport.destroy_crypto_key_version), "__call__" ) as call: call.return_value = resources.CryptoKeyVersion() @@ -5842,7 +6312,7 @@ async def test_destroy_crypto_key_version_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.destroy_crypto_key_version), "__call__" + type(client.transport.destroy_crypto_key_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKeyVersion() @@ -5865,7 +6335,7 @@ def test_destroy_crypto_key_version_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.destroy_crypto_key_version), "__call__" + type(client.transport.destroy_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -5901,7 +6371,7 @@ async def test_destroy_crypto_key_version_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.destroy_crypto_key_version), "__call__" + type(client.transport.destroy_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -5948,7 +6418,7 @@ def test_restore_crypto_key_version( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.restore_crypto_key_version), "__call__" + type(client.transport.restore_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion( @@ -5969,6 +6439,7 @@ def test_restore_crypto_key_version( assert args[0] == service.RestoreCryptoKeyVersionRequest() # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" @@ -5994,19 +6465,39 @@ def test_restore_crypto_key_version_from_dict(): test_restore_crypto_key_version(request_type=dict) +def test_restore_crypto_key_version_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 = KeyManagementServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: + client.restore_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + + assert args[0] == service.RestoreCryptoKeyVersionRequest() + + @pytest.mark.asyncio -async def test_restore_crypto_key_version_async(transport: str = "grpc_asyncio"): +async def test_restore_crypto_key_version_async( + transport: str = "grpc_asyncio", request_type=service.RestoreCryptoKeyVersionRequest +): client = KeyManagementServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. - request = service.RestoreCryptoKeyVersionRequest() + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.restore_crypto_key_version), "__call__" + type(client.transport.restore_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -6026,7 +6517,7 @@ async def test_restore_crypto_key_version_async(transport: str = "grpc_asyncio") assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == request + assert args[0] == service.RestoreCryptoKeyVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.CryptoKeyVersion) @@ -6050,6 +6541,11 @@ async def test_restore_crypto_key_version_async(transport: str = "grpc_asyncio") assert response.import_failure_reason == "import_failure_reason_value" +@pytest.mark.asyncio +async def test_restore_crypto_key_version_async_from_dict(): + await test_restore_crypto_key_version_async(request_type=dict) + + def test_restore_crypto_key_version_field_headers(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) @@ -6060,7 +6556,7 @@ def test_restore_crypto_key_version_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.restore_crypto_key_version), "__call__" + type(client.transport.restore_crypto_key_version), "__call__" ) as call: call.return_value = resources.CryptoKeyVersion() @@ -6089,7 +6585,7 @@ async def test_restore_crypto_key_version_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.restore_crypto_key_version), "__call__" + type(client.transport.restore_crypto_key_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKeyVersion() @@ -6112,7 +6608,7 @@ def test_restore_crypto_key_version_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.restore_crypto_key_version), "__call__" + type(client.transport.restore_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -6148,7 +6644,7 @@ async def test_restore_crypto_key_version_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.restore_crypto_key_version), "__call__" + type(client.transport.restore_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -6218,7 +6714,7 @@ def test_transport_instance(): credentials=credentials.AnonymousCredentials(), ) client = KeyManagementServiceClient(transport=transport) - assert client._transport is transport + assert client.transport is transport def test_transport_get_channel(): @@ -6254,7 +6750,7 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client._transport, transports.KeyManagementServiceGrpcTransport,) + assert isinstance(client.transport, transports.KeyManagementServiceGrpcTransport,) def test_key_management_service_base_transport_error(): @@ -6375,6 +6871,56 @@ def test_key_management_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ], +) +def test_key_management_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/cloudkms", + ), + 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_key_management_service_host_no_port(): client = KeyManagementServiceClient( credentials=credentials.AnonymousCredentials(), @@ -6382,7 +6928,7 @@ def test_key_management_service_host_no_port(): api_endpoint="cloudkms.googleapis.com" ), ) - assert client._transport._host == "cloudkms.googleapis.com:443" + assert client.transport._host == "cloudkms.googleapis.com:443" def test_key_management_service_host_with_port(): @@ -6392,11 +6938,11 @@ def test_key_management_service_host_with_port(): api_endpoint="cloudkms.googleapis.com:8000" ), ) - assert client._transport._host == "cloudkms.googleapis.com:8000" + assert client.transport._host == "cloudkms.googleapis.com:8000" def test_key_management_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.KeyManagementServiceGrpcTransport( @@ -6404,10 +6950,11 @@ def test_key_management_service_grpc_transport_channel(): ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None def test_key_management_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.KeyManagementServiceGrpcAsyncIOTransport( @@ -6415,8 +6962,11 @@ def test_key_management_service_grpc_asyncio_transport_channel(): ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" + 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", [ @@ -6431,7 +6981,7 @@ def test_key_management_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 @@ -6463,10 +7013,17 @@ def test_key_management_service_transport_channel_mtls_with_client_cert_source( ), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel + 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", [ @@ -6482,7 +7039,7 @@ def test_key_management_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 @@ -6506,6 +7063,10 @@ def test_key_management_service_transport_channel_mtls_with_adc(transport_class) ), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel @@ -6540,11 +7101,11 @@ def test_parse_crypto_key_path(): def test_crypto_key_version_path(): - project = "squid" - location = "clam" - key_ring = "whelk" - crypto_key = "octopus" - crypto_key_version = "oyster" + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( project=project, @@ -6561,11 +7122,11 @@ def test_crypto_key_version_path(): def test_parse_crypto_key_version_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "key_ring": "mussel", - "crypto_key": "winkle", - "crypto_key_version": "nautilus", + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", } path = KeyManagementServiceClient.crypto_key_version_path(**expected) @@ -6575,10 +7136,10 @@ def test_parse_crypto_key_version_path(): def test_import_job_path(): - project = "squid" - location = "clam" - key_ring = "whelk" - import_job = "octopus" + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + import_job = "nautilus" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format( project=project, location=location, key_ring=key_ring, import_job=import_job, @@ -6591,10 +7152,10 @@ def test_import_job_path(): def test_parse_import_job_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "key_ring": "cuttlefish", - "import_job": "mussel", + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "import_job": "clam", } path = KeyManagementServiceClient.import_job_path(**expected) @@ -6604,9 +7165,9 @@ def test_parse_import_job_path(): def test_key_ring_path(): - project = "squid" - location = "clam" - key_ring = "whelk" + project = "whelk" + location = "octopus" + key_ring = "oyster" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format( project=project, location=location, key_ring=key_ring, @@ -6617,9 +7178,9 @@ def test_key_ring_path(): def test_parse_key_ring_path(): expected = { - "project": "octopus", - "location": "oyster", - "key_ring": "nudibranch", + "project": "nudibranch", + "location": "cuttlefish", + "key_ring": "mussel", } path = KeyManagementServiceClient.key_ring_path(**expected) @@ -6628,6 +7189,142 @@ def test_parse_key_ring_path(): assert expected == actual +def test_public_key_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + actual = KeyManagementServiceClient.public_key_path( + project, location, key_ring, crypto_key, crypto_key_version + ) + assert expected == actual + + +def test_parse_public_key_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = KeyManagementServiceClient.public_key_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_public_key_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = KeyManagementServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = KeyManagementServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + + expected = "folders/{folder}".format(folder=folder,) + actual = KeyManagementServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = KeyManagementServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + + expected = "organizations/{organization}".format(organization=organization,) + actual = KeyManagementServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = KeyManagementServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + + expected = "projects/{project}".format(project=project,) + actual = KeyManagementServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = KeyManagementServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = KeyManagementServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = KeyManagementServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_location_path(path) + assert expected == actual + + def test_client_withDEFAULT_CLIENT_INFO(): client_info = gapic_v1.client_info.ClientInfo() @@ -6659,7 +7356,7 @@ def test_set_iam_policy(transport: str = "grpc"): request = iam_policy.SetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy(version=774, etag=b"etag_blob",) @@ -6690,9 +7387,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): request = iam_policy.SetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( policy.Policy(version=774, etag=b"etag_blob",) @@ -6723,7 +7418,7 @@ def test_set_iam_policy_field_headers(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.set_iam_policy(request) @@ -6750,9 +7445,7 @@ async def test_set_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.set_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.set_iam_policy(request) @@ -6770,7 +7463,7 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.set_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -6783,6 +7476,25 @@ def test_set_iam_policy_from_dict(): call.assert_called() +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + def test_get_iam_policy(transport: str = "grpc"): client = KeyManagementServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, @@ -6793,7 +7505,7 @@ def test_get_iam_policy(transport: str = "grpc"): request = iam_policy.GetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy(version=774, etag=b"etag_blob",) @@ -6824,9 +7536,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): request = iam_policy.GetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( policy.Policy(version=774, etag=b"etag_blob",) @@ -6857,7 +7567,7 @@ def test_get_iam_policy_field_headers(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = policy.Policy() client.get_iam_policy(request) @@ -6884,9 +7594,7 @@ async def test_get_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._client._transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) await client.get_iam_policy(request) @@ -6904,7 +7612,7 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_iam_policy), "__call__") as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = policy.Policy() @@ -6917,6 +7625,25 @@ def test_get_iam_policy_from_dict(): call.assert_called() +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + def test_test_iam_permissions(transport: str = "grpc"): client = KeyManagementServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, @@ -6928,7 +7655,7 @@ def test_test_iam_permissions(transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse( @@ -6961,7 +7688,7 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -6992,7 +7719,7 @@ def test_test_iam_permissions_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = iam_policy.TestIamPermissionsResponse() @@ -7021,7 +7748,7 @@ async def test_test_iam_permissions_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( iam_policy.TestIamPermissionsResponse() @@ -7043,7 +7770,7 @@ def test_test_iam_permissions_from_dict(): client = KeyManagementServiceClient(credentials=credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client._transport.test_iam_permissions), "__call__" + type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = iam_policy.TestIamPermissionsResponse() @@ -7055,3 +7782,26 @@ def test_test_iam_permissions_from_dict(): } ) call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called()