From 0596c88f906a920e7f1d775fe42f40f76c7a30ff Mon Sep 17 00:00:00 2001 From: Mend Renovate Date: Mon, 23 Jan 2023 16:31:26 +0000 Subject: [PATCH 1/9] chore(deps): update all dependencies (#333) --- samples/snippets/requirements.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 539381c..cf4bb56 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-private-ca==1.6.0 -google-cloud-kms==2.14.0 -google-cloud-monitoring==2.14.0 \ No newline at end of file +google-cloud-private-ca==1.6.1 +google-cloud-kms==2.14.1 +google-cloud-monitoring==2.14.1 \ No newline at end of file From 35b4a316c546c07f5d7b28147afe89c346a089c9 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 25 Jan 2023 11:42:06 -0500 Subject: [PATCH 2/9] chore: Update gapic-generator-python to v1.8.2 (#334) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.2 PiperOrigin-RevId: 504289125 Source-Link: https://github.com/googleapis/googleapis/commit/38a48a44a44279e9cf9f2f864b588958a2d87491 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b2dc22663dbe47a972c8d8c2f8a4df013dafdcbc Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjJkYzIyNjYzZGJlNDdhOTcyYzhkOGMyZjhhNGRmMDEzZGFmZGNiYyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- .coveragerc | 1 + google/cloud/security/privateca_v1/__init__.py | 2 +- google/cloud/security/privateca_v1beta1/__init__.py | 2 +- .../snippet_metadata_google.cloud.security.privateca.v1.json | 2 +- ...nippet_metadata_google.cloud.security.privateca.v1beta1.json | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.coveragerc b/.coveragerc index 422581a..eeab431 100644 --- a/.coveragerc +++ b/.coveragerc @@ -5,6 +5,7 @@ branch = True show_missing = True omit = google/cloud/security/privateca/__init__.py + google/cloud/security/privateca/gapic_version.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER diff --git a/google/cloud/security/privateca_v1/__init__.py b/google/cloud/security/privateca_v1/__init__.py index 30932ac..313174b 100644 --- a/google/cloud/security/privateca_v1/__init__.py +++ b/google/cloud/security/privateca_v1/__init__.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.security.privateca import gapic_version as package_version +from google.cloud.security.privateca_v1 import gapic_version as package_version __version__ = package_version.__version__ diff --git a/google/cloud/security/privateca_v1beta1/__init__.py b/google/cloud/security/privateca_v1beta1/__init__.py index 43ace52..a04f5ac 100644 --- a/google/cloud/security/privateca_v1beta1/__init__.py +++ b/google/cloud/security/privateca_v1beta1/__init__.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.security.privateca import gapic_version as package_version +from google.cloud.security.privateca_v1beta1 import gapic_version as package_version __version__ = package_version.__version__ diff --git a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json index 4c49e54..2ae53b3 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-private-ca", - "version": "1.6.1" + "version": "0.1.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json index 98e5b66..d9af1f5 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-private-ca", - "version": "1.6.1" + "version": "0.1.0" }, "snippets": [ { From c01ca6210fdad05cacbb8f637d698488e37251ed Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 30 Jan 2023 16:44:32 +0000 Subject: [PATCH 3/9] chore: fix prerelease_deps nox session [autoapprove] (#335) Source-Link: https://togithub.com/googleapis/synthtool/commit/26c7505b2f76981ec1707b851e1595c8c06e90fc Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 --- .github/.OwlBot.lock.yaml | 2 +- noxfile.py | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 889f77d..f0f3b24 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 + digest: sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 diff --git a/noxfile.py b/noxfile.py index e716318..95e58c5 100644 --- a/noxfile.py +++ b/noxfile.py @@ -189,9 +189,9 @@ def unit(session): def install_systemtest_dependencies(session, *constraints): # Use pre-release gRPC for system tests. - # Exclude version 1.49.0rc1 which has a known issue. - # See https://github.com/grpc/grpc/pull/30642 - session.install("--pre", "grpcio!=1.49.0rc1") + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) @@ -346,9 +346,7 @@ def prerelease_deps(session): unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES session.install(*unit_deps_all) system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS + SYSTEM_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_EXTERNAL_DEPENDENCIES ) session.install(*system_deps_all) @@ -378,8 +376,8 @@ def prerelease_deps(session): # dependency of grpc "six", "googleapis-common-protos", - # Exclude version 1.49.0rc1 which has a known issue. See https://github.com/grpc/grpc/pull/30642 - "grpcio!=1.49.0rc1", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", "grpcio-status", "google-api-core", "proto-plus", From e3786935084c3f904955a030ce59ec9f26cd908d Mon Sep 17 00:00:00 2001 From: Remigiusz Samborski Date: Wed, 1 Feb 2023 11:00:19 +0100 Subject: [PATCH 4/9] chore: Samples migration to python-docs-samples (#336) Samples migration to python-docs-samples in scope of monorepo migration --- samples/snippets/README.md | 4 + samples/snippets/activate_subordinate_ca.py | 87 ------ samples/snippets/conftest.py | 83 ----- samples/snippets/create_ca_pool.py | 53 ---- samples/snippets/create_certificate.py | 102 ------ .../snippets/create_certificate_authority.py | 97 ------ samples/snippets/create_certificate_csr.py | 74 ----- .../snippets/create_certificate_template.py | 82 ----- samples/snippets/create_subordinate_ca.py | 101 ------ samples/snippets/delete_ca_pool.py | 45 --- .../snippets/delete_certificate_authority.py | 76 ----- .../snippets/delete_certificate_template.py | 52 ---- .../snippets/disable_certificate_authority.py | 58 ---- .../snippets/enable_certificate_authority.py | 61 ---- samples/snippets/filter_certificates.py | 49 --- samples/snippets/list_ca_pools.py | 46 --- .../snippets/list_certificate_authorities.py | 42 --- .../snippets/list_certificate_templates.py | 44 --- samples/snippets/list_certificates.py | 46 --- .../snippets/monitor_certificate_authority.py | 77 ----- samples/snippets/noxfile.py | 292 ------------------ samples/snippets/noxfile_config.py | 38 --- samples/snippets/requirements-test.txt | 3 - samples/snippets/requirements.txt | 3 - samples/snippets/revoke_certificate.py | 65 ---- samples/snippets/test_ca_pools.py | 85 ----- .../snippets/test_certificate_authorities.py | 119 ------- samples/snippets/test_certificates.py | 96 ------ .../test_crud_certificate_templates.py | 71 ----- samples/snippets/test_subordinate_ca.py | 113 ------- .../undelete_certificate_authority.py | 68 ---- .../update_ca_pool_issuance_policy.py | 97 ------ .../snippets/update_certificate_authority.py | 71 ----- .../snippets/update_certificate_template.py | 87 ------ 34 files changed, 4 insertions(+), 2483 deletions(-) create mode 100644 samples/snippets/README.md delete mode 100644 samples/snippets/activate_subordinate_ca.py delete mode 100644 samples/snippets/conftest.py delete mode 100644 samples/snippets/create_ca_pool.py delete mode 100644 samples/snippets/create_certificate.py delete mode 100644 samples/snippets/create_certificate_authority.py delete mode 100644 samples/snippets/create_certificate_csr.py delete mode 100644 samples/snippets/create_certificate_template.py delete mode 100644 samples/snippets/create_subordinate_ca.py delete mode 100644 samples/snippets/delete_ca_pool.py delete mode 100644 samples/snippets/delete_certificate_authority.py delete mode 100644 samples/snippets/delete_certificate_template.py delete mode 100644 samples/snippets/disable_certificate_authority.py delete mode 100644 samples/snippets/enable_certificate_authority.py delete mode 100644 samples/snippets/filter_certificates.py delete mode 100644 samples/snippets/list_ca_pools.py delete mode 100644 samples/snippets/list_certificate_authorities.py delete mode 100644 samples/snippets/list_certificate_templates.py delete mode 100644 samples/snippets/list_certificates.py delete mode 100644 samples/snippets/monitor_certificate_authority.py delete mode 100644 samples/snippets/noxfile.py delete mode 100644 samples/snippets/noxfile_config.py delete mode 100644 samples/snippets/requirements-test.txt delete mode 100644 samples/snippets/requirements.txt delete mode 100644 samples/snippets/revoke_certificate.py delete mode 100644 samples/snippets/test_ca_pools.py delete mode 100644 samples/snippets/test_certificate_authorities.py delete mode 100644 samples/snippets/test_certificates.py delete mode 100644 samples/snippets/test_crud_certificate_templates.py delete mode 100644 samples/snippets/test_subordinate_ca.py delete mode 100644 samples/snippets/undelete_certificate_authority.py delete mode 100644 samples/snippets/update_ca_pool_issuance_policy.py delete mode 100644 samples/snippets/update_certificate_authority.py delete mode 100644 samples/snippets/update_certificate_template.py diff --git a/samples/snippets/README.md b/samples/snippets/README.md new file mode 100644 index 0000000..d818d55 --- /dev/null +++ b/samples/snippets/README.md @@ -0,0 +1,4 @@ +Samples migrated +================ + +New location: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/privateca/snippets \ No newline at end of file diff --git a/samples/snippets/activate_subordinate_ca.py b/samples/snippets/activate_subordinate_ca.py deleted file mode 100644 index ad6d9b5..0000000 --- a/samples/snippets/activate_subordinate_ca.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_activate_subordinateca] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def activate_subordinate_ca( - project_id: str, - location: str, - ca_pool_name: str, - subordinate_ca_name: str, - pem_ca_certificate: str, - ca_name: str, -) -> None: - """ - Activate a subordinate Certificate Authority (CA). - *Prerequisite*: Get the Certificate Signing Resource (CSR) of the subordinate CA signed by another CA. Pass in the signed - certificate and (issuer CA's name or the issuer CA's Certificate chain). - *Post*: After activating the subordinate CA, it should be enabled before issuing certificates. - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: set it to the CA Pool under which the CA should be created. - pem_ca_certificate: the signed certificate, obtained by signing the CSR. - subordinate_ca_name: the CA to be activated. - ca_name: The name of the certificate authority which signed the CSR. - If an external CA (CA not present in Google Cloud) was used for signing, - then use the CA's issuerCertificateChain. - """ - - ca_service_client = privateca_v1.CertificateAuthorityServiceClient() - - subordinate_ca_path = ca_service_client.certificate_authority_path( - project_id, location, ca_pool_name, subordinate_ca_name - ) - ca_path = ca_service_client.certificate_authority_path( - project_id, location, ca_pool_name, ca_name - ) - - # Set CA subordinate config. - subordinate_config = privateca_v1.SubordinateConfig( - # Follow one of the below methods: - # Method 1: If issuer CA is in Google Cloud, set the Certificate Authority Name. - certificate_authority=ca_path, - # Method 2: If issuer CA is external to Google Cloud, set the issuer's certificate chain. - # The certificate chain of the CA (which signed the CSR) from leaf to root. - # pem_issuer_chain=privateca_v1.SubordinateConfig.SubordinateConfigChain( - # pem_certificates=issuer_certificate_chain, - # ) - ) - - # Construct the "Activate CA Request". - request = privateca_v1.ActivateCertificateAuthorityRequest( - name=subordinate_ca_path, - # The signed certificate. - pem_ca_certificate=pem_ca_certificate, - subordinate_config=subordinate_config, - ) - - # Activate the CA - operation = ca_service_client.activate_certificate_authority(request=request) - result = operation.result() - - print("Operation result:", result) - - # The current state will be STAGED. - # The Subordinate CA has to be ENABLED before issuing certificates. - print( - f"Current state: {ca_service_client.get_certificate_authority(name=subordinate_ca_path).state}" - ) - - -# [END privateca_activate_subordinateca] diff --git a/samples/snippets/conftest.py b/samples/snippets/conftest.py deleted file mode 100644 index d958e01..0000000 --- a/samples/snippets/conftest.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import uuid - -import google.auth -import pytest - -from create_ca_pool import create_ca_pool -from create_certificate_authority import create_certificate_authority -from create_certificate_template import create_certificate_template -from delete_ca_pool import delete_ca_pool -from delete_certificate_authority import delete_certificate_authority -from delete_certificate_template import delete_certificate_template - -PROJECT = google.auth.default()[1] -LOCATION = "us-central1" -COMMON_NAME = "COMMON_NAME" -ORGANIZATION = "ORGANIZATION" -CA_DURATION = 1000000 - - -def generate_name() -> str: - return "test-" + uuid.uuid4().hex[:10] - - -@pytest.fixture -def ca_pool(): - CA_POOL_NAME = generate_name() - - create_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - - yield CA_POOL_NAME - - delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - - -@pytest.fixture -def certificate_authority(ca_pool): - CA_NAME = generate_name() - - create_certificate_authority( - PROJECT, LOCATION, ca_pool, CA_NAME, COMMON_NAME, ORGANIZATION, CA_DURATION - ) - - yield ca_pool, CA_NAME - - delete_certificate_authority(PROJECT, LOCATION, ca_pool, CA_NAME) - - -@pytest.fixture -def deleted_certificate_authority(ca_pool): - CA_NAME = generate_name() - - create_certificate_authority( - PROJECT, LOCATION, ca_pool, CA_NAME, COMMON_NAME, ORGANIZATION, CA_DURATION - ) - - delete_certificate_authority(PROJECT, LOCATION, ca_pool, CA_NAME) - - yield ca_pool, CA_NAME - - -@pytest.fixture -def certificate_template(): - TEMPLATE_NAME = generate_name() - - create_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME) - - yield TEMPLATE_NAME - - delete_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME) diff --git a/samples/snippets/create_ca_pool.py b/samples/snippets/create_ca_pool.py deleted file mode 100644 index 2b11785..0000000 --- a/samples/snippets/create_ca_pool.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_create_ca_pool] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def create_ca_pool(project_id: str, location: str, ca_pool_name: str) -> None: - """ - Create a Certificate Authority pool. All certificates created under this CA pool will - follow the same issuance policy, IAM policies,etc., - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: a unique name for the ca pool. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - ca_pool = privateca_v1.CaPool( - # Set the tier (see: https://cloud.google.com/certificate-authority-service/docs/tiers). - tier=privateca_v1.CaPool.Tier.ENTERPRISE, - ) - location_path = caServiceClient.common_location_path(project_id, location) - - # Create the pool request. - request = privateca_v1.CreateCaPoolRequest( - parent=location_path, - ca_pool_id=ca_pool_name, - ca_pool=ca_pool, - ) - - # Create the CA pool. - operation = caServiceClient.create_ca_pool(request=request) - - print("Operation result:", operation.result()) - - -# [END privateca_create_ca_pool] diff --git a/samples/snippets/create_certificate.py b/samples/snippets/create_certificate.py deleted file mode 100644 index 0533056..0000000 --- a/samples/snippets/create_certificate.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_create_certificate] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.protobuf import duration_pb2 - - -def create_certificate( - project_id: str, - location: str, - ca_pool_name: str, - ca_name: str, - certificate_name: str, - common_name: str, - domain_name: str, - certificate_lifetime: int, - public_key_bytes: bytes, -) -> None: - """ - Create a Certificate which is issued by the Certificate Authority present in the CA Pool. - The key used to sign the certificate is created by the Cloud KMS. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: set a unique name for the CA pool. - ca_name: the name of the certificate authority which issues the certificate. - certificate_name: set a unique name for the certificate. - common_name: a title for your certificate. - domain_name: fully qualified domain name for your certificate. - certificate_lifetime: the validity of the certificate in seconds. - public_key_bytes: public key used in signing the certificates. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - # The public key used to sign the certificate can be generated using any crypto library/framework. - # Also you can use Cloud KMS to retrieve an already created public key. - # For more info, see: https://cloud.google.com/kms/docs/retrieve-public-key. - - # Set the Public Key and its format. - public_key = privateca_v1.PublicKey( - key=public_key_bytes, - format_=privateca_v1.PublicKey.KeyFormat.PEM, - ) - - subject_config = privateca_v1.CertificateConfig.SubjectConfig( - subject=privateca_v1.Subject(common_name=common_name), - subject_alt_name=privateca_v1.SubjectAltNames(dns_names=[domain_name]), - ) - - # Set the X.509 fields required for the certificate. - x509_parameters = privateca_v1.X509Parameters( - key_usage=privateca_v1.KeyUsage( - base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions( - digital_signature=True, - key_encipherment=True, - ), - extended_key_usage=privateca_v1.KeyUsage.ExtendedKeyUsageOptions( - server_auth=True, - client_auth=True, - ), - ), - ) - - # Create certificate. - certificate = privateca_v1.Certificate( - config=privateca_v1.CertificateConfig( - public_key=public_key, - subject_config=subject_config, - x509_config=x509_parameters, - ), - lifetime=duration_pb2.Duration(seconds=certificate_lifetime), - ) - - # Create the Certificate Request. - request = privateca_v1.CreateCertificateRequest( - parent=caServiceClient.ca_pool_path(project_id, location, ca_pool_name), - certificate_id=certificate_name, - certificate=certificate, - issuing_certificate_authority_id=ca_name, - ) - result = caServiceClient.create_certificate(request=request) - - print("Certificate creation result:", result) - - -# [END privateca_create_certificate] diff --git a/samples/snippets/create_certificate_authority.py b/samples/snippets/create_certificate_authority.py deleted file mode 100644 index 2cb0c65..0000000 --- a/samples/snippets/create_certificate_authority.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_create_ca] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.protobuf import duration_pb2 - - -def create_certificate_authority( - project_id: str, - location: str, - ca_pool_name: str, - ca_name: str, - common_name: str, - organization: str, - ca_duration: int, -) -> None: - """ - Create Certificate Authority which is the root CA in the given CA Pool. This CA will be - responsible for signing certificates within this pool. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: set it to the CA Pool under which the CA should be created. - ca_name: unique name for the CA. - common_name: a title for your certificate authority. - organization: the name of your company for your certificate authority. - ca_duration: the validity of the certificate authority in seconds. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - # Set the types of Algorithm used to create a cloud KMS key. - key_version_spec = privateca_v1.CertificateAuthority.KeyVersionSpec( - algorithm=privateca_v1.CertificateAuthority.SignHashAlgorithm.RSA_PKCS1_4096_SHA256 - ) - - # Set CA subject config. - subject_config = privateca_v1.CertificateConfig.SubjectConfig( - subject=privateca_v1.Subject(common_name=common_name, organization=organization) - ) - - # Set the key usage options for X.509 fields. - x509_parameters = privateca_v1.X509Parameters( - key_usage=privateca_v1.KeyUsage( - base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions( - crl_sign=True, - cert_sign=True, - ) - ), - ca_options=privateca_v1.X509Parameters.CaOptions( - is_ca=True, - ), - ) - - # Set certificate authority settings. - certificate_authority = privateca_v1.CertificateAuthority( - # CertificateAuthority.Type.SELF_SIGNED denotes that this CA is a root CA. - type_=privateca_v1.CertificateAuthority.Type.SELF_SIGNED, - key_spec=key_version_spec, - config=privateca_v1.CertificateConfig( - subject_config=subject_config, - x509_config=x509_parameters, - ), - lifetime=duration_pb2.Duration(seconds=ca_duration), - ) - - ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name) - - # Create the CertificateAuthorityRequest. - request = privateca_v1.CreateCertificateAuthorityRequest( - parent=ca_pool_path, - certificate_authority_id=ca_name, - certificate_authority=certificate_authority, - ) - - operation = caServiceClient.create_certificate_authority(request=request) - result = operation.result() - - print("Operation result:", result) - - -# [END privateca_create_ca] diff --git a/samples/snippets/create_certificate_csr.py b/samples/snippets/create_certificate_csr.py deleted file mode 100644 index d3bc892..0000000 --- a/samples/snippets/create_certificate_csr.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_create_certificate_csr] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.protobuf import duration_pb2 - - -def create_certificate_csr( - project_id: str, - location: str, - ca_pool_name: str, - ca_name: str, - certificate_name: str, - certificate_lifetime: int, - pem_csr: str, -) -> None: - """ - Create a Certificate which is issued by the specified Certificate Authority (CA). - The certificate details and the public key is provided as a Certificate Signing Request (CSR). - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: set a unique name for the CA pool. - ca_name: the name of the certificate authority to sign the CSR. - certificate_name: set a unique name for the certificate. - certificate_lifetime: the validity of the certificate in seconds. - pem_csr: set the Certificate Issuing Request in the pem encoded format. - """ - - ca_service_client = privateca_v1.CertificateAuthorityServiceClient() - - # The public key used to sign the certificate can be generated using any crypto library/framework. - # Also you can use Cloud KMS to retrieve an already created public key. - # For more info, see: https://cloud.google.com/kms/docs/retrieve-public-key. - - # Create certificate with CSR. - # The pem_csr contains the public key and the domain details required. - certificate = privateca_v1.Certificate( - pem_csr=pem_csr, - lifetime=duration_pb2.Duration(seconds=certificate_lifetime), - ) - - # Create the Certificate Request. - # Set the CA which is responsible for creating the certificate with the provided CSR. - request = privateca_v1.CreateCertificateRequest( - parent=ca_service_client.ca_pool_path(project_id, location, ca_pool_name), - certificate_id=certificate_name, - certificate=certificate, - issuing_certificate_authority_id=ca_name, - ) - response = ca_service_client.create_certificate(request=request) - - print(f"Certificate created successfully: {response.name}") - - # Get the signed certificate and the issuer chain list. - print(f"Signed certificate: {response.pem_certificate}") - print(f"Issuer chain list: {response.pem_certificate_chain}") - - -# [END privateca_create_certificate_csr] diff --git a/samples/snippets/create_certificate_template.py b/samples/snippets/create_certificate_template.py deleted file mode 100644 index 988ebfc..0000000 --- a/samples/snippets/create_certificate_template.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2022 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. - -# [START privateca_create_certificate_template] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.type import expr_pb2 - - -def create_certificate_template( - project_id: str, - location: str, - certificate_template_id: str, -) -> None: - """ - Create a Certificate template. These templates can be reused for common - certificate issuance scenarios. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - certificate_template_id: set a unique name for the certificate template. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - # Describes any predefined X.509 values set by this template. - # The provided extensions are copied over to certificate requests that use this template. - x509_parameters = privateca_v1.X509Parameters( - key_usage=privateca_v1.KeyUsage( - base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions( - digital_signature=True, - key_encipherment=True, - ), - extended_key_usage=privateca_v1.KeyUsage.ExtendedKeyUsageOptions( - server_auth=True, - ), - ), - ca_options=privateca_v1.X509Parameters.CaOptions( - is_ca=False, - ), - ) - - # CEL expression that is evaluated against the Subject and - # Subject Alternative Name of the certificate before it is issued. - expr = expr_pb2.Expr(expression="subject_alt_names.all(san, san.type == DNS)") - - # Set the certificate issuance schema. - certificate_template = privateca_v1.CertificateTemplate( - predefined_values=x509_parameters, - identity_constraints=privateca_v1.CertificateIdentityConstraints( - cel_expression=expr, - allow_subject_passthrough=False, - allow_subject_alt_names_passthrough=False, - ), - ) - - # Request to create a certificate template. - request = privateca_v1.CreateCertificateTemplateRequest( - parent=caServiceClient.common_location_path(project_id, location), - certificate_template=certificate_template, - certificate_template_id=certificate_template_id, - ) - operation = caServiceClient.create_certificate_template(request=request) - result = operation.result() - - print("Operation result:", result) - - -# [END privateca_create_certificate_template] diff --git a/samples/snippets/create_subordinate_ca.py b/samples/snippets/create_subordinate_ca.py deleted file mode 100644 index 426a047..0000000 --- a/samples/snippets/create_subordinate_ca.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_create_subordinateca] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.protobuf import duration_pb2 - - -def create_subordinate_ca( - project_id: str, - location: str, - ca_pool_name: str, - subordinate_ca_name: str, - common_name: str, - organization: str, - domain: str, - ca_duration: int, -) -> None: - """ - Create Certificate Authority (CA) which is the subordinate CA in the given CA Pool. - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: set it to the CA Pool under which the CA should be created. - subordinate_ca_name: unique name for the Subordinate CA. - common_name: a title for your certificate authority. - organization: the name of your company for your certificate authority. - domain: the name of your company for your certificate authority. - ca_duration: the validity of the certificate authority in seconds. - """ - - ca_service_client = privateca_v1.CertificateAuthorityServiceClient() - - # Set the type of Algorithm - key_version_spec = privateca_v1.CertificateAuthority.KeyVersionSpec( - algorithm=privateca_v1.CertificateAuthority.SignHashAlgorithm.RSA_PKCS1_4096_SHA256 - ) - - # Set CA subject config. - subject_config = privateca_v1.CertificateConfig.SubjectConfig( - subject=privateca_v1.Subject( - common_name=common_name, organization=organization - ), - # Set the fully qualified domain name. - subject_alt_name=privateca_v1.SubjectAltNames(dns_names=[domain]), - ) - - # Set the key usage options for X.509 fields. - x509_parameters = privateca_v1.X509Parameters( - key_usage=privateca_v1.KeyUsage( - base_key_usage=privateca_v1.KeyUsage.KeyUsageOptions( - crl_sign=True, - cert_sign=True, - ) - ), - ca_options=privateca_v1.X509Parameters.CaOptions( - is_ca=True, - ), - ) - - # Set certificate authority settings. - certificate_authority = privateca_v1.CertificateAuthority( - type_=privateca_v1.CertificateAuthority.Type.SUBORDINATE, - key_spec=key_version_spec, - config=privateca_v1.CertificateConfig( - subject_config=subject_config, - x509_config=x509_parameters, - ), - # Set the CA validity duration. - lifetime=duration_pb2.Duration(seconds=ca_duration), - ) - - ca_pool_path = ca_service_client.ca_pool_path(project_id, location, ca_pool_name) - - # Create the CertificateAuthorityRequest. - request = privateca_v1.CreateCertificateAuthorityRequest( - parent=ca_pool_path, - certificate_authority_id=subordinate_ca_name, - certificate_authority=certificate_authority, - ) - - operation = ca_service_client.create_certificate_authority(request=request) - result = operation.result() - - print(f"Operation result: {result}") - - -# [END privateca_create_subordinateca] diff --git a/samples/snippets/delete_ca_pool.py b/samples/snippets/delete_ca_pool.py deleted file mode 100644 index e90f89b..0000000 --- a/samples/snippets/delete_ca_pool.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_delete_ca_pool] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def delete_ca_pool(project_id: str, location: str, ca_pool_name: str) -> None: - """ - Delete the CA pool as mentioned by the ca_pool_name. - Before deleting the pool, all CAs in the pool MUST BE deleted. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: the name of the CA pool to be deleted. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name) - - # Create the Delete request. - request = privateca_v1.DeleteCaPoolRequest(name=ca_pool_path) - - # Delete the CA Pool. - caServiceClient.delete_ca_pool(request=request) - - print("Deleted CA Pool:", ca_pool_name) - - -# [END privateca_delete_ca_pool] diff --git a/samples/snippets/delete_certificate_authority.py b/samples/snippets/delete_certificate_authority.py deleted file mode 100644 index fc0b73e..0000000 --- a/samples/snippets/delete_certificate_authority.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_delete_ca] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def delete_certificate_authority( - project_id: str, location: str, ca_pool_name: str, ca_name: str -) -> None: - """ - Delete the Certificate Authority from the specified CA pool. - Before deletion, the CA must be disabled and must not contain any active certificates. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: the name of the CA pool under which the CA is present. - ca_name: the name of the CA to be deleted. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - ca_path = caServiceClient.certificate_authority_path( - project_id, location, ca_pool_name, ca_name - ) - - # Check if the CA is enabled. - ca_state = caServiceClient.get_certificate_authority(name=ca_path).state - print(ca_state) - if ca_state == privateca_v1.CertificateAuthority.State.ENABLED: - print( - "Please disable the Certificate Authority before deletion ! Current state:", - ca_state, - ) - - # Create the DeleteCertificateAuthorityRequest. - # Setting the ignore_active_certificates to True will delete the CA - # even if it contains active certificates. Care should be taken to re-anchor - # the certificates to new CA before deleting. - request = privateca_v1.DeleteCertificateAuthorityRequest( - name=ca_path, ignore_active_certificates=False - ) - - # Delete the Certificate Authority. - operation = caServiceClient.delete_certificate_authority(request=request) - result = operation.result() - - print("Operation result", result) - - # Get the current CA state. - ca_state = caServiceClient.get_certificate_authority(name=ca_path).state - - # Check if the CA has been deleted. - if ca_state == privateca_v1.CertificateAuthority.State.DELETED: - print("Successfully deleted Certificate Authority:", ca_name) - else: - print( - "Unable to delete Certificate Authority. Please try again ! Current state:", - ca_state, - ) - - -# [END privateca_delete_ca] diff --git a/samples/snippets/delete_certificate_template.py b/samples/snippets/delete_certificate_template.py deleted file mode 100644 index e44dca1..0000000 --- a/samples/snippets/delete_certificate_template.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2022 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. - -# [START privateca_delete_certificate_template] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def delete_certificate_template( - project_id: str, - location: str, - certificate_template_id: str, -) -> None: - """ - Delete the certificate template present in the given project and location. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - certificate_template_id: set a unique name for the certificate template. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - # Request to delete a certificate template. - request = privateca_v1.DeleteCertificateTemplateRequest( - name=caServiceClient.certificate_template_path( - project_id, - location, - certificate_template_id, - ) - ) - operation = caServiceClient.delete_certificate_template(request=request) - result = operation.result() - - print("Operation result", result) - print("Deleted certificate template:", certificate_template_id) - - -# [END privateca_delete_certificate_template] diff --git a/samples/snippets/disable_certificate_authority.py b/samples/snippets/disable_certificate_authority.py deleted file mode 100644 index 5ec4e7c..0000000 --- a/samples/snippets/disable_certificate_authority.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_disable_ca] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def disable_certificate_authority( - project_id: str, location: str, ca_pool_name: str, ca_name: str -) -> None: - """ - Disable a Certificate Authority which is present in the given CA pool. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: the name of the CA pool under which the CA is present. - ca_name: the name of the CA to be disabled. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - ca_path = caServiceClient.certificate_authority_path( - project_id, location, ca_pool_name, ca_name - ) - - # Create the Disable Certificate Authority Request. - request = privateca_v1.DisableCertificateAuthorityRequest(name=ca_path) - - # Disable the Certificate Authority. - operation = caServiceClient.disable_certificate_authority(request=request) - result = operation.result() - - print("Operation result:", result) - - # Get the current CA state. - ca_state = caServiceClient.get_certificate_authority(name=ca_path).state - - # Check if the CA is disabled. - if ca_state == privateca_v1.CertificateAuthority.State.DISABLED: - print("Disabled Certificate Authority:", ca_name) - else: - print("Cannot disable the Certificate Authority ! Current CA State:", ca_state) - - -# [END privateca_disable_ca] diff --git a/samples/snippets/enable_certificate_authority.py b/samples/snippets/enable_certificate_authority.py deleted file mode 100644 index a6ecd35..0000000 --- a/samples/snippets/enable_certificate_authority.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_enable_ca] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def enable_certificate_authority( - project_id: str, location: str, ca_pool_name: str, ca_name: str -) -> None: - """ - Enable the Certificate Authority present in the given ca pool. - CA cannot be enabled if it has been already deleted. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: the name of the CA pool under which the CA is present. - ca_name: the name of the CA to be enabled. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - ca_path = caServiceClient.certificate_authority_path( - project_id, location, ca_pool_name, ca_name - ) - - # Create the Enable Certificate Authority Request. - request = privateca_v1.EnableCertificateAuthorityRequest( - name=ca_path, - ) - - # Enable the Certificate Authority. - operation = caServiceClient.enable_certificate_authority(request=request) - result = operation.result() - - print("Operation result:", result) - - # Get the current CA state. - ca_state = caServiceClient.get_certificate_authority(name=ca_path).state - - # Check if the CA is enabled. - if ca_state == privateca_v1.CertificateAuthority.State.ENABLED: - print("Enabled Certificate Authority:", ca_name) - else: - print("Cannot enable the Certificate Authority ! Current CA State:", ca_state) - - -# [END privateca_enable_ca] diff --git a/samples/snippets/filter_certificates.py b/samples/snippets/filter_certificates.py deleted file mode 100644 index c9789dc..0000000 --- a/samples/snippets/filter_certificates.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_filter_certificate] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def filter_certificates( - project_id: str, location: str, ca_pool_name: str, filter_condition: str -) -> None: - """ - Filter certificates based on a condition and list them. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: name of the CA pool which contains the certificates to be listed. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name) - - # Create the certificate request and set the filter condition. - request = privateca_v1.ListCertificatesRequest( - parent=ca_pool_path, - filter=filter_condition, - ) - - # Retrieve and print the certificate names. - print("Available certificates: ") - for cert in caServiceClient.list_certificates(request=request): - print(f"- {cert.name}") - - -# [END privateca_filter_certificate] diff --git a/samples/snippets/list_ca_pools.py b/samples/snippets/list_ca_pools.py deleted file mode 100644 index b072045..0000000 --- a/samples/snippets/list_ca_pools.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_list_ca_pool] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def list_ca_pools(project_id: str, location: str) -> None: - """ - List all CA pools present in the given project and location. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - location_path = caServiceClient.common_location_path(project_id, location) - - request = privateca_v1.ListCaPoolsRequest(parent=location_path) - - print("Available CA pools:") - - for ca_pool in caServiceClient.list_ca_pools(request=request): - ca_pool_name = ca_pool.name - # ca_pool.name represents the full resource name of the - # format 'projects/{project-id}/locations/{location}/ca-pools/{ca-pool-name}'. - # Hence stripping it down to just pool name. - print(caServiceClient.parse_ca_pool_path(ca_pool_name)["ca_pool"]) - - -# [END privateca_list_ca_pool] diff --git a/samples/snippets/list_certificate_authorities.py b/samples/snippets/list_certificate_authorities.py deleted file mode 100644 index 19fd37d..0000000 --- a/samples/snippets/list_certificate_authorities.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_list_ca] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def list_certificate_authorities( - project_id: str, location: str, ca_pool_name: str -) -> None: - """ - List all Certificate authorities present in the given CA Pool. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: the name of the CA pool under which the CAs to be listed are present. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name) - - # List the CA name and its corresponding state. - for ca in caServiceClient.list_certificate_authorities(parent=ca_pool_path): - print(ca.name, "is", ca.state) - - -# [END privateca_list_ca] diff --git a/samples/snippets/list_certificate_templates.py b/samples/snippets/list_certificate_templates.py deleted file mode 100644 index 8e8c4c7..0000000 --- a/samples/snippets/list_certificate_templates.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2022 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. - -# [START privateca_list_certificate_template] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def list_certificate_templates(project_id: str, location: str) -> None: - """ - List the certificate templates present in the given project and location. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - # List Templates Request. - request = privateca_v1.ListCertificateTemplatesRequest( - parent=caServiceClient.common_location_path(project_id, location), - ) - - print("Available certificate templates:") - for certificate_template in caServiceClient.list_certificate_templates( - request=request - ): - print(certificate_template.name) - - -# [END privateca_list_certificate_template] diff --git a/samples/snippets/list_certificates.py b/samples/snippets/list_certificates.py deleted file mode 100644 index 9c04ed9..0000000 --- a/samples/snippets/list_certificates.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_list_certificate] - -import google.cloud.security.privateca_v1 as privateca_v1 - - -def list_certificates( - project_id: str, - location: str, - ca_pool_name: str, -) -> None: - """ - List Certificates present in the given CA pool. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: name of the CA pool which contains the certificates to be listed. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name) - - # Retrieve and print the certificate names. - print(f"Available certificates in CA pool {ca_pool_name}:") - for certificate in caServiceClient.list_certificates(parent=ca_pool_path): - print(certificate.name) - - -# [END privateca_list_certificate] diff --git a/samples/snippets/monitor_certificate_authority.py b/samples/snippets/monitor_certificate_authority.py deleted file mode 100644 index bac5e02..0000000 --- a/samples/snippets/monitor_certificate_authority.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2022 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. - -# [START privateca_monitor_ca_expiry] -import google.cloud.monitoring_v3 as monitoring_v3 - - -def create_ca_monitor_policy(project_id: str) -> None: - """ - Create a monitoring policy that notifies you 30 days before a managed CA expires. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - """ - - alertPolicyServiceClient = monitoring_v3.AlertPolicyServiceClient() - notificationChannelServiceClient = monitoring_v3.NotificationChannelServiceClient() - - # Query which indicates the resource to monitor and the constraints. - # Here, the alert policy notifies you 30 days before a managed CA expires. - # For more information on creating queries, see: https://cloud.google.com/monitoring/mql/alerts - query = ( - "fetch privateca.googleapis.com/CertificateAuthority" - "| metric 'privateca.googleapis.com/ca/cert_chain_expiration'" - "| group_by 5m," - "[value_cert_chain_expiration_mean: mean(value.cert_chain_expiration)]" - "| every 5m" - "| condition val() < 2.592e+06 's'" - ) - - # Create a notification channel. - notification_channel = monitoring_v3.NotificationChannel( - type_="email", - labels={"email_address": "python-docs-samples-testing@google.com"}, - ) - channel = notificationChannelServiceClient.create_notification_channel( - name=notificationChannelServiceClient.common_project_path(project_id), - notification_channel=notification_channel, - ) - - # Set the query and notification channel. - alert_policy = monitoring_v3.AlertPolicy( - display_name="policy-name", - conditions=[ - monitoring_v3.AlertPolicy.Condition( - display_name="ca-cert-chain-expiration", - condition_monitoring_query_language=monitoring_v3.AlertPolicy.Condition.MonitoringQueryLanguageCondition( - query=query, - ), - ) - ], - combiner=monitoring_v3.AlertPolicy.ConditionCombinerType.AND, - notification_channels=[channel.name], - ) - - policy = alertPolicyServiceClient.create_alert_policy( - name=notificationChannelServiceClient.common_project_path(project_id), - alert_policy=alert_policy, - ) - - print("Monitoring policy successfully created!", policy.name) - - -# [END privateca_monitor_ca_expiry] diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py deleted file mode 100644 index de104db..0000000 --- a/samples/snippets/noxfile.py +++ /dev/null @@ -1,292 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, Optional - -import nox - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8") - else: - session.install("flake8", "flake8-annotations") - - args = FLAKE8_COMMON_ARGS + [ - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( - "**/test_*.py", recursive=True - ) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) - elif "pytest-xdist" in packages: - concurrent_args.extend(["-n", "auto"]) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py deleted file mode 100644 index 4a4db8c..0000000 --- a/samples/snippets/noxfile_config.py +++ /dev/null @@ -1,38 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Default TEST_CONFIG_OVERRIDE for python repos. - -# You can copy this file into your directory, then it will be inported from -# the noxfile.py. - -# The source of truth: -# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py - -TEST_CONFIG_OVERRIDE = { - # You can opt out from the test for specific Python versions. - "ignored_versions": ["2.7"], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - # "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - "gcloud_project_env": "BUILD_SPECIFIC_GCLOUD_PROJECT", - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt deleted file mode 100644 index 77d6f60..0000000 --- a/samples/snippets/requirements-test.txt +++ /dev/null @@ -1,3 +0,0 @@ -pytest==7.2.1 -google-auth==2.16.0 -cryptography==39.0.0 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt deleted file mode 100644 index cf4bb56..0000000 --- a/samples/snippets/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -google-cloud-private-ca==1.6.1 -google-cloud-kms==2.14.1 -google-cloud-monitoring==2.14.1 \ No newline at end of file diff --git a/samples/snippets/revoke_certificate.py b/samples/snippets/revoke_certificate.py deleted file mode 100644 index fa0d2f2..0000000 --- a/samples/snippets/revoke_certificate.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import sys - -# isort: split -# [START privateca_revoke_certificate] - -import google.cloud.security.privateca_v1 as privateca_v1 - - -def revoke_certificate( - project_id: str, - location: str, - ca_pool_name: str, - certificate_name: str, -) -> None: - """ - Revoke an issued certificate. Once revoked, the certificate will become invalid and will expire post its lifetime. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: name for the CA pool which contains the certificate. - certificate_name: name of the certificate to be revoked. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - # Create Certificate Path. - certificate_path = caServiceClient.certificate_path( - project_id, location, ca_pool_name, certificate_name - ) - - # Create Revoke Certificate Request and specify the appropriate revocation reason. - request = privateca_v1.RevokeCertificateRequest( - name=certificate_path, reason=privateca_v1.RevocationReason.PRIVILEGE_WITHDRAWN - ) - result = caServiceClient.revoke_certificate(request=request) - - print("Certificate revoke result:", result) - - -# [END privateca_revoke_certificate] - -if __name__ == "__main__": - revoke_certificate( - project_id=sys.argv[1], - location=sys.argv[2], - ca_pool_name=sys.argv[3], - certificate_name=sys.argv[4], - ) diff --git a/samples/snippets/test_ca_pools.py b/samples/snippets/test_ca_pools.py deleted file mode 100644 index 5fc17a5..0000000 --- a/samples/snippets/test_ca_pools.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -import typing -import uuid - -import google.auth - -from create_ca_pool import create_ca_pool -from delete_ca_pool import delete_ca_pool -from list_ca_pools import list_ca_pools -from update_ca_pool_issuance_policy import update_ca_pool_issuance_policy - -PROJECT = google.auth.default()[1] -LOCATION = "us-central1" - - -def generate_name() -> str: - return "test-" + uuid.uuid4().hex[:10] - - -def test_create_ca_pool(ca_pool, capsys: typing.Any) -> None: - CA_POOL_NAME = generate_name() - - create_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - - out, _ = capsys.readouterr() - - assert re.search( - f'Operation result: name: "projects/{PROJECT}/locations/{LOCATION}/caPools/{CA_POOL_NAME}"', - out, - ) - - delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - - -def test_list_ca_pools(capsys: typing.Any) -> None: - CA_POOL_NAME_1 = generate_name() - CA_POOL_NAME_2 = generate_name() - - create_ca_pool(PROJECT, LOCATION, CA_POOL_NAME_1) - create_ca_pool(PROJECT, LOCATION, CA_POOL_NAME_2) - list_ca_pools(PROJECT, LOCATION) - - out, _ = capsys.readouterr() - - assert "Available CA pools:" in out - assert f"{CA_POOL_NAME_1}\n" in out - assert f"{CA_POOL_NAME_2}\n" in out - - delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME_1) - delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME_2) - - -def test_delete_ca_pool(capsys: typing.Any) -> None: - CA_POOL_NAME = generate_name() - - create_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - - out, _ = capsys.readouterr() - - assert re.search(f"Deleted CA Pool: {CA_POOL_NAME}", out) - - -def test_update_ca_pool_issuance_policy(ca_pool, capsys: typing.Any) -> None: - CA_POOL_NAME = ca_pool - - update_ca_pool_issuance_policy(PROJECT, LOCATION, CA_POOL_NAME) - - out, _ = capsys.readouterr() - - assert "CA Pool Issuance policy has been updated successfully!" in out diff --git a/samples/snippets/test_certificate_authorities.py b/samples/snippets/test_certificate_authorities.py deleted file mode 100644 index daac5bc..0000000 --- a/samples/snippets/test_certificate_authorities.py +++ /dev/null @@ -1,119 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -import typing -import uuid - -import google.auth - -from create_ca_pool import create_ca_pool -from create_certificate_authority import create_certificate_authority -from delete_ca_pool import delete_ca_pool -from delete_certificate_authority import delete_certificate_authority -from disable_certificate_authority import disable_certificate_authority -from enable_certificate_authority import enable_certificate_authority -from monitor_certificate_authority import create_ca_monitor_policy -from undelete_certificate_authority import undelete_certificate_authority -from update_certificate_authority import update_ca_label - -PROJECT = google.auth.default()[1] -LOCATION = "us-central1" -COMMON_NAME = "COMMON_NAME" -ORGANIZATION = "ORGANIZATION" -CA_DURATION = 1000000 - - -def generate_name() -> str: - return "i" + uuid.uuid4().hex[:10] - - -def test_create_certificate(capsys: typing.Any) -> None: - CA_POOL_NAME = generate_name() - CA_NAME = generate_name() - - create_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - create_certificate_authority( - PROJECT, LOCATION, CA_POOL_NAME, CA_NAME, COMMON_NAME, ORGANIZATION, CA_DURATION - ) - - out, _ = capsys.readouterr() - - assert re.search( - f'Operation result: name: "projects/{PROJECT}/locations/{LOCATION}/caPools/{CA_POOL_NAME}/certificateAuthorities/{CA_NAME}"', - out, - ) - - delete_certificate_authority(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - - -def test_enable_and_disable_certificate_authority( - certificate_authority, capsys: typing.Any -) -> None: - CA_POOL_NAME, CA_NAME = certificate_authority - - enable_certificate_authority(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - disable_certificate_authority(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - - out, _ = capsys.readouterr() - - assert re.search( - f"Enabled Certificate Authority: {CA_NAME}", - out, - ) - assert re.search( - f"Disabled Certificate Authority: {CA_NAME}", - out, - ) - - -def test_undelete_certificate_authority( - deleted_certificate_authority, capsys: typing.Any -) -> None: - CA_POOL_NAME, CA_NAME = deleted_certificate_authority - - undelete_certificate_authority(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - delete_certificate_authority(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - delete_ca_pool(PROJECT, LOCATION, CA_POOL_NAME) - - out, _ = capsys.readouterr() - assert re.search( - f"Successfully undeleted Certificate Authority: {CA_NAME}", - out, - ) - assert re.search( - f"Successfully deleted Certificate Authority: {CA_NAME}", - out, - ) - - -def test_update_certificate_authority( - certificate_authority, capsys: typing.Any -) -> None: - CA_POOL_NAME, CA_NAME = certificate_authority - - update_ca_label(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - - out, _ = capsys.readouterr() - - assert "Successfully updated the labels !" in out - - -def test_create_monitor_ca_policy(capsys: typing.Any) -> None: - create_ca_monitor_policy(PROJECT) - - out, _ = capsys.readouterr() - - assert "Monitoring policy successfully created!" in out diff --git a/samples/snippets/test_certificates.py b/samples/snippets/test_certificates.py deleted file mode 100644 index 35fcac3..0000000 --- a/samples/snippets/test_certificates.py +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import re -import time -import typing -import uuid - -from cryptography.hazmat.backends.openssl.backend import backend -from cryptography.hazmat.primitives.asymmetric import rsa -from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat -import google.auth - -from create_certificate import create_certificate -from disable_certificate_authority import disable_certificate_authority -from enable_certificate_authority import enable_certificate_authority -from filter_certificates import filter_certificates -from revoke_certificate import revoke_certificate - -PROJECT = google.auth.default()[1] -LOCATION = "us-central1" -COMMON_NAME = "COMMON_NAME" -ORGANIZATION = "ORGANIZATION" -CERTIFICATE_LIFETIME = 1000000 -DOMAIN_NAME = "domain.com" - - -def generate_name() -> str: - return "test-" + uuid.uuid4().hex[:10] - - -def test_create_and_revoke_certificate_authority( - certificate_authority, capsys: typing.Any -) -> None: - CERT_NAME = generate_name() - - CA_POOL_NAME, CA_NAME = certificate_authority - enable_certificate_authority(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - - private_key = rsa.generate_private_key( - public_exponent=65537, key_size=2048, backend=backend - ) - - public_key_bytes = private_key.public_key().public_bytes( - Encoding.PEM, PublicFormat.SubjectPublicKeyInfo - ) - - # Wait while crypto key is generating - time.sleep(5) - - create_certificate( - PROJECT, - LOCATION, - CA_POOL_NAME, - CA_NAME, - CERT_NAME, - COMMON_NAME, - DOMAIN_NAME, - CERTIFICATE_LIFETIME, - public_key_bytes, - ) - - FILTER_CONDITION = ( - f"certificate_description.subject_description.subject.common_name={COMMON_NAME}" - ) - filter_certificates(PROJECT, LOCATION, CA_POOL_NAME, FILTER_CONDITION) - - revoke_certificate( - PROJECT, - LOCATION, - CA_POOL_NAME, - CERT_NAME, - ) - - disable_certificate_authority(PROJECT, LOCATION, CA_POOL_NAME, CA_NAME) - - out, _ = capsys.readouterr() - assert "Certificate creation result:" in out - assert "Available certificates:" in out - assert re.search( - f"- projects/.*/locations/{LOCATION}/caPools/{CA_POOL_NAME}/certificates/{CERT_NAME}", - out, - ) - assert "Certificate revoke result:" in out diff --git a/samples/snippets/test_crud_certificate_templates.py b/samples/snippets/test_crud_certificate_templates.py deleted file mode 100644 index 8c2c94b..0000000 --- a/samples/snippets/test_crud_certificate_templates.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import re -import typing -import uuid - -import google.auth - -from create_certificate_template import create_certificate_template -from delete_certificate_template import delete_certificate_template -from list_certificate_templates import list_certificate_templates -from update_certificate_template import update_certificate_template - -PROJECT = google.auth.default()[1] -LOCATION = "us-central1" -COMMON_NAME = "COMMON_NAME" -ORGANIZATION = "ORGANIZATION" -CA_DURATION = 1000000 - - -def generate_name() -> str: - return "i" + uuid.uuid4().hex[:10] - - -def test_create_delete_certificate_template(capsys: typing.Any) -> None: - TEMPLATE_NAME = generate_name() - - create_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME) - delete_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME) - - out, _ = capsys.readouterr() - - assert re.search( - f'Operation result: name: "projects/{PROJECT}/locations/{LOCATION}/certificateTemplates/{TEMPLATE_NAME}"', - out, - ) - - assert re.search(f"Deleted certificate template: {TEMPLATE_NAME}", out) - - -def test_list_certificate_templates(certificate_template, capsys: typing.Any) -> None: - TEMPLATE_NAME = certificate_template - - list_certificate_templates(PROJECT, LOCATION) - - out, _ = capsys.readouterr() - - assert "Available certificate templates:" in out - assert f"{TEMPLATE_NAME}\n" in out - - -def test_update_certificate_template(certificate_template, capsys: typing.Any) -> None: - TEMPLATE_NAME = certificate_template - - update_certificate_template(PROJECT, LOCATION, TEMPLATE_NAME) - - out, _ = capsys.readouterr() - - assert "Successfully updated the certificate template!" in out diff --git a/samples/snippets/test_subordinate_ca.py b/samples/snippets/test_subordinate_ca.py deleted file mode 100644 index 1fe2d29..0000000 --- a/samples/snippets/test_subordinate_ca.py +++ /dev/null @@ -1,113 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import re -import typing -import uuid - -import google.auth -import google.cloud.security.privateca_v1 as privateca_v1 - -from activate_subordinate_ca import activate_subordinate_ca -from create_certificate_csr import create_certificate_csr -from create_subordinate_ca import create_subordinate_ca -from revoke_certificate import revoke_certificate - -PROJECT = google.auth.default()[1] -LOCATION = "us-central1" -COMMON_NAME = "COMMON_NAME" -ORGANIZATION = "ORGANIZATION" -CA_DURATION = CERTIFICATE_LIFETIME = 1000000 -DOMAIN_NAME = "domain.com" - - -def generate_name() -> str: - return "test-" + uuid.uuid4().hex[:10] - - -def test_subordinate_certificate_authority( - certificate_authority, capsys: typing.Any -) -> None: - CSR_CERT_NAME = generate_name() - SUBORDINATE_CA_NAME = generate_name() - - CA_POOL_NAME, ROOT_CA_NAME = certificate_authority - - # 1. Create a Subordinate Certificate Authority. - create_subordinate_ca( - PROJECT, - LOCATION, - CA_POOL_NAME, - SUBORDINATE_CA_NAME, - COMMON_NAME, - ORGANIZATION, - DOMAIN_NAME, - CA_DURATION, - ) - - # 2. Fetch CSR of the given CA. - ca_service_client = privateca_v1.CertificateAuthorityServiceClient() - - ca_path = ca_service_client.certificate_authority_path( - PROJECT, LOCATION, CA_POOL_NAME, SUBORDINATE_CA_NAME - ) - response = ca_service_client.fetch_certificate_authority_csr(name=ca_path) - pem_csr = response.pem_csr - - # 3. Sign the CSR and create a certificate. - create_certificate_csr( - PROJECT, - LOCATION, - CA_POOL_NAME, - ROOT_CA_NAME, - CSR_CERT_NAME, - CERTIFICATE_LIFETIME, - pem_csr, - ) - - # 4. Get certificate PEM format - certificate_name = ca_service_client.certificate_path( - PROJECT, LOCATION, CA_POOL_NAME, CSR_CERT_NAME - ) - pem_certificate = ca_service_client.get_certificate( - name=certificate_name - ).pem_certificate - - # 5. Activate Subordinate CA - activate_subordinate_ca( - PROJECT, - LOCATION, - CA_POOL_NAME, - SUBORDINATE_CA_NAME, - pem_certificate, - ROOT_CA_NAME, - ) - - revoke_certificate( - PROJECT, - LOCATION, - CA_POOL_NAME, - CSR_CERT_NAME, - ) - - out, _ = capsys.readouterr() - - assert re.search( - f'Operation result: name: "projects/{PROJECT}/locations/{LOCATION}/caPools/{CA_POOL_NAME}/certificateAuthorities/{SUBORDINATE_CA_NAME}"', - out, - ) - - assert "Certificate created successfully" in out - assert f"Current state: {privateca_v1.CertificateAuthority.State.STAGED}" in out diff --git a/samples/snippets/undelete_certificate_authority.py b/samples/snippets/undelete_certificate_authority.py deleted file mode 100644 index f436f89..0000000 --- a/samples/snippets/undelete_certificate_authority.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_undelete_ca] -import google.cloud.security.privateca_v1 as privateca_v1 - - -def undelete_certificate_authority( - project_id: str, location: str, ca_pool_name: str, ca_name: str -) -> None: - """ - Restore a deleted CA, if still within the grace period of 30 days. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: the name of the CA pool under which the deleted CA is present. - ca_name: the name of the CA to be restored (undeleted). - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - ca_path = caServiceClient.certificate_authority_path( - project_id, location, ca_pool_name, ca_name - ) - - # Confirm if the CA is in DELETED stage. - ca_state = caServiceClient.get_certificate_authority(name=ca_path).state - if ca_state != privateca_v1.CertificateAuthority.State.DELETED: - print("CA is not deleted !") - return - - # Create the Request. - request = privateca_v1.UndeleteCertificateAuthorityRequest(name=ca_path) - - # Undelete the CA. - operation = caServiceClient.undelete_certificate_authority(request=request) - result = operation.result() - - print("Operation result", result) - - # Get the current CA state. - ca_state = caServiceClient.get_certificate_authority(name=ca_path).state - - # CA state changes from DELETED to DISABLED if successfully restored. - # Confirm if the CA is DISABLED. - if ca_state == privateca_v1.CertificateAuthority.State.DISABLED: - print("Successfully undeleted Certificate Authority:", ca_name) - else: - print( - "Unable to restore the Certificate Authority! Please try again! Current state:", - ca_state, - ) - - -# [END privateca_undelete_ca] diff --git a/samples/snippets/update_ca_pool_issuance_policy.py b/samples/snippets/update_ca_pool_issuance_policy.py deleted file mode 100644 index 750c6f3..0000000 --- a/samples/snippets/update_ca_pool_issuance_policy.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START privateca_set_issuance_policy] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.protobuf import field_mask_pb2 -from google.type import expr_pb2 - - -def update_ca_pool_issuance_policy( - project_id: str, - location: str, - ca_pool_name: str, -) -> None: - """ - Update the issuance policy for a CA Pool. All certificates issued from this CA Pool should - meet the issuance policy - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: a unique name for the ca pool. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - ca_pool_path = caServiceClient.ca_pool_path(project_id, location, ca_pool_name) - - # Set the updated issuance policy for the CA Pool. - # This particular issuance policy allows only SANs that - # have DNS Names as "us.google.org" or ending in ".google.com". */ - expr = expr_pb2.Expr( - expression='subject_alt_names.all(san, san.type == DNS && (san.value == "us.google.org" || san.value.endsWith(".google.com")) )' - ) - - issuance_policy = privateca_v1.CaPool.IssuancePolicy( - identity_constraints=privateca_v1.CertificateIdentityConstraints( - allow_subject_passthrough=True, - allow_subject_alt_names_passthrough=True, - cel_expression=expr, - ), - ) - - ca_pool = privateca_v1.CaPool( - name=ca_pool_path, - issuance_policy=issuance_policy, - ) - - # 1. Set the CA pool with updated values. - # 2. Set the update mask to specify which properties of the CA Pool should be updated. - # Only the properties specified in the mask will be updated. Make sure that the mask fields - # match the updated issuance policy. - # For more info on constructing path for update mask, see: - # https://cloud.google.com/certificate-authority-service/docs/reference/rest/v1/projects.locations.caPools#issuancepolicy */ - request = privateca_v1.UpdateCaPoolRequest( - ca_pool=ca_pool, - update_mask=field_mask_pb2.FieldMask( - paths=[ - "issuance_policy.identity_constraints.allow_subject_alt_names_passthrough", - "issuance_policy.identity_constraints.allow_subject_passthrough", - "issuance_policy.identity_constraints.cel_expression", - ], - ), - ) - operation = caServiceClient.update_ca_pool(request=request) - result = operation.result() - - print("Operation result", result) - - # Get the CA Pool's issuance policy and verify if the fields have been successfully updated. - issuance_policy = caServiceClient.get_ca_pool(name=ca_pool_path).issuance_policy - - # Similarly, you can check for other modified fields as well. - if ( - issuance_policy.identity_constraints.allow_subject_passthrough - and issuance_policy.identity_constraints.allow_subject_alt_names_passthrough - ): - print("CA Pool Issuance policy has been updated successfully!") - return - - print("Error in updating CA Pool Issuance policy! Please try again!") - - -# [END privateca_set_issuance_policy] diff --git a/samples/snippets/update_certificate_authority.py b/samples/snippets/update_certificate_authority.py deleted file mode 100644 index 9acd3f8..0000000 --- a/samples/snippets/update_certificate_authority.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2022 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. - -# [START privateca_update_ca_label] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.protobuf import field_mask_pb2 - - -def update_ca_label( - project_id: str, - location: str, - ca_pool_name: str, - ca_name: str, -) -> None: - """ - Update the labels in a certificate authority. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - ca_pool_name: set it to the CA Pool under which the CA should be updated. - ca_name: unique name for the CA. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - # Set the parent path and the new labels. - ca_parent = caServiceClient.certificate_authority_path( - project_id, location, ca_pool_name, ca_name - ) - certificate_authority = privateca_v1.CertificateAuthority( - name=ca_parent, - labels={"env": "test"}, - ) - - # Create a request to update the CA. - request = privateca_v1.UpdateCertificateAuthorityRequest( - certificate_authority=certificate_authority, - update_mask=field_mask_pb2.FieldMask(paths=["labels"]), - ) - - operation = caServiceClient.update_certificate_authority(request=request) - result = operation.result() - - print("Operation result:", result) - - # Get the updated CA and check if it contains the new label. - - certificate_authority = caServiceClient.get_certificate_authority(name=ca_parent) - - if ( - "env" in certificate_authority.labels - and certificate_authority.labels["env"] == "test" - ): - print("Successfully updated the labels !") - - -# [END privateca_update_ca_label] diff --git a/samples/snippets/update_certificate_template.py b/samples/snippets/update_certificate_template.py deleted file mode 100644 index ac05be8..0000000 --- a/samples/snippets/update_certificate_template.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2022 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. - -# [START privateca_update_certificate_template] -import google.cloud.security.privateca_v1 as privateca_v1 -from google.protobuf import field_mask_pb2 - - -def update_certificate_template( - project_id: str, - location: str, - certificate_template_id: str, -) -> None: - """ - Update an existing certificate template. - - Args: - project_id: project ID or project number of the Cloud project you want to use. - location: location you want to use. For a list of locations, see: https://cloud.google.com/certificate-authority-service/docs/locations. - certificate_template_id: set a unique name for the certificate template. - """ - - caServiceClient = privateca_v1.CertificateAuthorityServiceClient() - - certificate_name = caServiceClient.certificate_template_path( - project_id, - location, - certificate_template_id, - ) - - # Set the parent name and the properties to be updated. - certificate_template = privateca_v1.CertificateTemplate( - name=certificate_name, - identity_constraints=privateca_v1.CertificateIdentityConstraints( - allow_subject_passthrough=False, - allow_subject_alt_names_passthrough=True, - ), - ) - - # Set the mask corresponding to the properties updated above. - field_mask = field_mask_pb2.FieldMask( - paths=[ - "identity_constraints.allow_subject_alt_names_passthrough", - "identity_constraints.allow_subject_passthrough", - ], - ) - - # Set the new template. - # Set the mask to specify which properties of the template should be updated. - request = privateca_v1.UpdateCertificateTemplateRequest( - certificate_template=certificate_template, - update_mask=field_mask, - ) - operation = caServiceClient.update_certificate_template(request=request) - result = operation.result() - - print("Operation result", result) - - # Get the updated certificate template and check if the properties have been updated. - cert_identity_constraints = caServiceClient.get_certificate_template( - name=certificate_name - ).identity_constraints - - if ( - not cert_identity_constraints.allow_subject_passthrough - and cert_identity_constraints.allow_subject_alt_names_passthrough - ): - print("Successfully updated the certificate template!") - return - - print("Error in updating certificate template!") - - -# [END privateca_update_certificate_template] From 0cf64744b60512861b645ef2b1d5e9bafcb9a596 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 7 Feb 2023 15:17:13 -0500 Subject: [PATCH 5/9] chore: Update gapic-generator-python to v1.8.4 (#337) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.4 PiperOrigin-RevId: 507808936 Source-Link: https://github.com/googleapis/googleapis/commit/64cf8492b21778ce62c66ecee81b468a293bfd4c Source-Link: https://github.com/googleapis/googleapis-gen/commit/53c48cac153d3b37f3d2c2dec4830cfd91ec4153 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTNjNDhjYWMxNTNkM2IzN2YzZDJjMmRlYzQ4MzBjZmQ5MWVjNDE1MyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- setup.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 13ae7f5..62e0ab6 100644 --- a/setup.py +++ b/setup.py @@ -57,9 +57,7 @@ if package.startswith("google") ] -namespaces = ["google"] -if "google.cloud" in packages: - namespaces.append("google.cloud") +namespaces = ["google", "google.cloud", "google.cloud.security"] setuptools.setup( name=name, From 45dffcf9c09306afee5abc6025246c264ce0cfc1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 8 Feb 2023 15:20:17 +0000 Subject: [PATCH 6/9] build(deps): bump cryptography from 38.0.3 to 39.0.1 in /synthtool/gcp/templates/python_library/.kokoro (#338) Source-Link: https://togithub.com/googleapis/synthtool/commit/bb171351c3946d3c3c32e60f5f18cee8c464ec51 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/requirements.txt | 49 ++++++++++++++++++--------------------- 2 files changed, 23 insertions(+), 28 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index f0f3b24..894fb6b 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f946c75373c2b0040e8e318c5e85d0cf46bc6e61d0a01f3ef94d8de974ac6790 + digest: sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 05dc467..096e480 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -113,33 +113,28 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==38.0.3 \ - --hash=sha256:068147f32fa662c81aebab95c74679b401b12b57494872886eb5c1139250ec5d \ - --hash=sha256:06fc3cc7b6f6cca87bd56ec80a580c88f1da5306f505876a71c8cfa7050257dd \ - --hash=sha256:25c1d1f19729fb09d42e06b4bf9895212292cb27bb50229f5aa64d039ab29146 \ - --hash=sha256:402852a0aea73833d982cabb6d0c3bb582c15483d29fb7085ef2c42bfa7e38d7 \ - --hash=sha256:4e269dcd9b102c5a3d72be3c45d8ce20377b8076a43cbed6f660a1afe365e436 \ - --hash=sha256:5419a127426084933076132d317911e3c6eb77568a1ce23c3ac1e12d111e61e0 \ - --hash=sha256:554bec92ee7d1e9d10ded2f7e92a5d70c1f74ba9524947c0ba0c850c7b011828 \ - --hash=sha256:5e89468fbd2fcd733b5899333bc54d0d06c80e04cd23d8c6f3e0542358c6060b \ - --hash=sha256:65535bc550b70bd6271984d9863a37741352b4aad6fb1b3344a54e6950249b55 \ - --hash=sha256:6ab9516b85bebe7aa83f309bacc5f44a61eeb90d0b4ec125d2d003ce41932d36 \ - --hash=sha256:6addc3b6d593cd980989261dc1cce38263c76954d758c3c94de51f1e010c9a50 \ - --hash=sha256:728f2694fa743a996d7784a6194da430f197d5c58e2f4e278612b359f455e4a2 \ - --hash=sha256:785e4056b5a8b28f05a533fab69febf5004458e20dad7e2e13a3120d8ecec75a \ - --hash=sha256:78cf5eefac2b52c10398a42765bfa981ce2372cbc0457e6bf9658f41ec3c41d8 \ - --hash=sha256:7f836217000342d448e1c9a342e9163149e45d5b5eca76a30e84503a5a96cab0 \ - --hash=sha256:8d41a46251bf0634e21fac50ffd643216ccecfaf3701a063257fe0b2be1b6548 \ - --hash=sha256:984fe150f350a3c91e84de405fe49e688aa6092b3525f407a18b9646f6612320 \ - --hash=sha256:9b24bcff7853ed18a63cfb0c2b008936a9554af24af2fb146e16d8e1aed75748 \ - --hash=sha256:b1b35d9d3a65542ed2e9d90115dfd16bbc027b3f07ee3304fc83580f26e43249 \ - --hash=sha256:b1b52c9e5f8aa2b802d48bd693190341fae201ea51c7a167d69fc48b60e8a959 \ - --hash=sha256:bbf203f1a814007ce24bd4d51362991d5cb90ba0c177a9c08825f2cc304d871f \ - --hash=sha256:be243c7e2bfcf6cc4cb350c0d5cdf15ca6383bbcb2a8ef51d3c9411a9d4386f0 \ - --hash=sha256:bfbe6ee19615b07a98b1d2287d6a6073f734735b49ee45b11324d85efc4d5cbd \ - --hash=sha256:c46837ea467ed1efea562bbeb543994c2d1f6e800785bd5a2c98bc096f5cb220 \ - --hash=sha256:dfb4f4dd568de1b6af9f4cda334adf7d72cf5bc052516e1b2608b683375dd95c \ - --hash=sha256:ed7b00096790213e09eb11c97cc6e2b757f15f3d2f85833cd2d3ec3fe37c1722 +cryptography==39.0.1 \ + --hash=sha256:0f8da300b5c8af9f98111ffd512910bc792b4c77392a9523624680f7956a99d4 \ + --hash=sha256:35f7c7d015d474f4011e859e93e789c87d21f6f4880ebdc29896a60403328f1f \ + --hash=sha256:5aa67414fcdfa22cf052e640cb5ddc461924a045cacf325cd164e65312d99502 \ + --hash=sha256:5d2d8b87a490bfcd407ed9d49093793d0f75198a35e6eb1a923ce1ee86c62b41 \ + --hash=sha256:6687ef6d0a6497e2b58e7c5b852b53f62142cfa7cd1555795758934da363a965 \ + --hash=sha256:6f8ba7f0328b79f08bdacc3e4e66fb4d7aab0c3584e0bd41328dce5262e26b2e \ + --hash=sha256:706843b48f9a3f9b9911979761c91541e3d90db1ca905fd63fee540a217698bc \ + --hash=sha256:807ce09d4434881ca3a7594733669bd834f5b2c6d5c7e36f8c00f691887042ad \ + --hash=sha256:83e17b26de248c33f3acffb922748151d71827d6021d98c70e6c1a25ddd78505 \ + --hash=sha256:96f1157a7c08b5b189b16b47bc9db2332269d6680a196341bf30046330d15388 \ + --hash=sha256:aec5a6c9864be7df2240c382740fcf3b96928c46604eaa7f3091f58b878c0bb6 \ + --hash=sha256:b0afd054cd42f3d213bf82c629efb1ee5f22eba35bf0eec88ea9ea7304f511a2 \ + --hash=sha256:ced4e447ae29ca194449a3f1ce132ded8fcab06971ef5f618605aacaa612beac \ + --hash=sha256:d1f6198ee6d9148405e49887803907fe8962a23e6c6f83ea7d98f1c0de375695 \ + --hash=sha256:e124352fd3db36a9d4a21c1aa27fd5d051e621845cb87fb851c08f4f75ce8be6 \ + --hash=sha256:e422abdec8b5fa8462aa016786680720d78bdce7a30c652b7fadf83a4ba35336 \ + --hash=sha256:ef8b72fa70b348724ff1218267e7f7375b8de4e8194d1636ee60510aae104cd0 \ + --hash=sha256:f0c64d1bd842ca2633e74a1a28033d139368ad959872533b1bab8c80e8240a0c \ + --hash=sha256:f24077a3b5298a5a06a8e0536e3ea9ec60e4c7ac486755e5fb6e6ea9b3500106 \ + --hash=sha256:fdd188c8a6ef8769f148f88f859884507b954cc64db6b52f66ef199bb9ad660a \ + --hash=sha256:fe913f20024eb2cb2f323e42a64bdf2911bb9738a15dba7d3cce48151034e3a8 # via # gcp-releasetool # secretstorage From b0a9c444d2a2928201d4ee83492f2938086cdbd9 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 27 Feb 2023 16:14:41 +0000 Subject: [PATCH 7/9] chore(python): upgrade gcp-releasetool in .kokoro [autoapprove] (#340) Source-Link: https://togithub.com/googleapis/synthtool/commit/5f2a6089f73abf06238fe4310f6a14d6f6d1eed3 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:8555f0e37e6261408f792bfd6635102d2da5ad73f8f09bcb24f25e6afb5fac97 --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/requirements.in | 2 +- .kokoro/requirements.txt | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 894fb6b..5fc5daa 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f62c53736eccb0c4934a3ea9316e0d57696bb49c1a7c86c726e9bb8a2f87dadf + digest: sha256:8555f0e37e6261408f792bfd6635102d2da5ad73f8f09bcb24f25e6afb5fac97 diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in index cbd7e77..882178c 100644 --- a/.kokoro/requirements.in +++ b/.kokoro/requirements.in @@ -1,5 +1,5 @@ gcp-docuploader -gcp-releasetool +gcp-releasetool>=1.10.5 # required for compatibility with cryptography>=39.x importlib-metadata typing-extensions twine diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 096e480..fa99c12 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -154,9 +154,9 @@ gcp-docuploader==0.6.4 \ --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf # via -r requirements.in -gcp-releasetool==1.10.0 \ - --hash=sha256:72a38ca91b59c24f7e699e9227c90cbe4dd71b789383cb0164b088abae294c83 \ - --hash=sha256:8c7c99320208383d4bb2b808c6880eb7a81424afe7cdba3c8d84b25f4f0e097d +gcp-releasetool==1.10.5 \ + --hash=sha256:174b7b102d704b254f2a26a3eda2c684fd3543320ec239baf771542a2e58e109 \ + --hash=sha256:e29d29927fe2ca493105a82958c6873bb2b90d503acac56be2c229e74de0eec9 # via -r requirements.in google-api-core==2.10.2 \ --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ From 423615cc7b1c4b893e062e86e780e021475a7d0c Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 2 Mar 2023 12:56:43 -0800 Subject: [PATCH 8/9] fix: Add `service_yaml` parameters to `privateca_py_gapic` (#339) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: Update gapic-generator-python to v1.8.5 PiperOrigin-RevId: 511892190 Source-Link: https://github.com/googleapis/googleapis/commit/a45d9c09c1287ffdf938f4e8083e791046c0b23b Source-Link: https://github.com/googleapis/googleapis-gen/commit/1907294b1d8365ea24f8c5f2e059a64124c4ed3b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMTkwNzI5NGIxZDgzNjVlYTI0ZjhjNWYyZTA1OWE2NDEyNGM0ZWQzYiJ9 fix: Add service_yaml_parameters to py_gapic_library BUILD.bazel targets PiperOrigin-RevId: 510187992 Source-Link: https://github.com/googleapis/googleapis/commit/5edc23561778df80d5293f20132765f8757a6b2c Source-Link: https://github.com/googleapis/googleapis-gen/commit/b0bedb72e4765a3e0b674a28c50ea0f9a9b26a89 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjBiZWRiNzJlNDc2NWEzZTBiNjc0YTI4YzUwZWEwZjlhOWIyNmE4OSJ9 feat: add X.509 Name Constraints support PiperOrigin-RevId: 509331611 Source-Link: https://github.com/googleapis/googleapis/commit/a57751bb8ef2e51a27115923a44c553eafc98faa Source-Link: https://github.com/googleapis/googleapis-gen/commit/f99e972b5210aa2a5d0fe7cb91fb0dca4c8a9032 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiZjk5ZTk3MmI1MjEwYWEyYTVkMGZlN2NiOTFmYjBkY2E0YzhhOTAzMiJ9 feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix: Add `service_yaml` parameters to `privateca_py_gapic` PiperOrigin-RevId: 513565852 Source-Link: https://github.com/googleapis/googleapis/commit/d83ff744bd8ace55bfeecd6bbe508a1bac154479 Source-Link: https://github.com/googleapis/googleapis-gen/commit/26d16e1f7e27cc886c746f09030a32677d0a8209 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMjZkMTZlMWY3ZTI3Y2M4ODZjNzQ2ZjA5MDMwYTMyNjc3ZDBhODIwOSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- .../security/privateca_v1/gapic_metadata.json | 150 + .../async_client.py | 713 +- .../certificate_authority_service/client.py | 715 +- .../transports/__init__.py | 7 + .../transports/base.py | 87 + .../transports/grpc.py | 189 + .../transports/grpc_asyncio.py | 189 + .../transports/rest.py | 5065 ++++++ .../security/privateca_v1/types/resources.py | 108 + .../security/privateca_v1/types/service.py | 172 +- .../privateca_v1beta1/gapic_metadata.json | 105 + .../certificate_authority_service/client.py | 2 + .../transports/__init__.py | 7 + .../transports/rest.py | 3035 ++++ .../privateca_v1beta1/types/resources.py | 2 + .../privateca_v1beta1/types/service.py | 2 + setup.py | 1 + testing/constraints-3.10.txt | 1 + testing/constraints-3.11.txt | 1 + testing/constraints-3.12.txt | 1 + testing/constraints-3.7.txt | 1 + testing/constraints-3.8.txt | 1 + testing/constraints-3.9.txt | 1 + .../test_certificate_authority_service.py | 13950 +++++++++++++++- .../test_certificate_authority_service.py | 7473 ++++++++- 25 files changed, 31083 insertions(+), 895 deletions(-) create mode 100644 google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py create mode 100644 google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py diff --git a/google/cloud/security/privateca_v1/gapic_metadata.json b/google/cloud/security/privateca_v1/gapic_metadata.json index 9eb6757..6aed41b 100644 --- a/google/cloud/security/privateca_v1/gapic_metadata.json +++ b/google/cloud/security/privateca_v1/gapic_metadata.json @@ -306,6 +306,156 @@ ] } } + }, + "rest": { + "libraryClient": "CertificateAuthorityServiceClient", + "rpcs": { + "ActivateCertificateAuthority": { + "methods": [ + "activate_certificate_authority" + ] + }, + "CreateCaPool": { + "methods": [ + "create_ca_pool" + ] + }, + "CreateCertificate": { + "methods": [ + "create_certificate" + ] + }, + "CreateCertificateAuthority": { + "methods": [ + "create_certificate_authority" + ] + }, + "CreateCertificateTemplate": { + "methods": [ + "create_certificate_template" + ] + }, + "DeleteCaPool": { + "methods": [ + "delete_ca_pool" + ] + }, + "DeleteCertificateAuthority": { + "methods": [ + "delete_certificate_authority" + ] + }, + "DeleteCertificateTemplate": { + "methods": [ + "delete_certificate_template" + ] + }, + "DisableCertificateAuthority": { + "methods": [ + "disable_certificate_authority" + ] + }, + "EnableCertificateAuthority": { + "methods": [ + "enable_certificate_authority" + ] + }, + "FetchCaCerts": { + "methods": [ + "fetch_ca_certs" + ] + }, + "FetchCertificateAuthorityCsr": { + "methods": [ + "fetch_certificate_authority_csr" + ] + }, + "GetCaPool": { + "methods": [ + "get_ca_pool" + ] + }, + "GetCertificate": { + "methods": [ + "get_certificate" + ] + }, + "GetCertificateAuthority": { + "methods": [ + "get_certificate_authority" + ] + }, + "GetCertificateRevocationList": { + "methods": [ + "get_certificate_revocation_list" + ] + }, + "GetCertificateTemplate": { + "methods": [ + "get_certificate_template" + ] + }, + "ListCaPools": { + "methods": [ + "list_ca_pools" + ] + }, + "ListCertificateAuthorities": { + "methods": [ + "list_certificate_authorities" + ] + }, + "ListCertificateRevocationLists": { + "methods": [ + "list_certificate_revocation_lists" + ] + }, + "ListCertificateTemplates": { + "methods": [ + "list_certificate_templates" + ] + }, + "ListCertificates": { + "methods": [ + "list_certificates" + ] + }, + "RevokeCertificate": { + "methods": [ + "revoke_certificate" + ] + }, + "UndeleteCertificateAuthority": { + "methods": [ + "undelete_certificate_authority" + ] + }, + "UpdateCaPool": { + "methods": [ + "update_ca_pool" + ] + }, + "UpdateCertificate": { + "methods": [ + "update_certificate" + ] + }, + "UpdateCertificateAuthority": { + "methods": [ + "update_certificate_authority" + ] + }, + "UpdateCertificateRevocationList": { + "methods": [ + "update_certificate_revocation_list" + ] + }, + "UpdateCertificateTemplate": { + "methods": [ + "update_certificate_template" + ] + } + } } } } diff --git a/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py b/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py index f93ceb5..ad8e751 100644 --- a/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py +++ b/google/cloud/security/privateca_v1/services/certificate_authority_service/async_client.py @@ -44,6 +44,10 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore @@ -344,7 +348,8 @@ async def sample_create_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -454,7 +459,8 @@ async def sample_get_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -561,7 +567,7 @@ async def sample_list_certificates(): Returns: google.cloud.security.privateca_v1.services.certificate_authority_service.pagers.ListCertificatesAsyncPager: Response message for - [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. + [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. Iterating over this object will yield results and resolve additional pages automatically. @@ -678,7 +684,8 @@ async def sample_revoke_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -796,7 +803,8 @@ async def sample_update_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -926,8 +934,9 @@ async def sample_activate_certificate_authority(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1075,8 +1084,9 @@ async def sample_create_certificate_authority(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1205,8 +1215,9 @@ async def sample_disable_certificate_authority(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1329,8 +1340,9 @@ async def sample_enable_certificate_authority(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1562,8 +1574,9 @@ async def sample_get_certificate_authority(): Returns: google.cloud.security.privateca_v1.types.CertificateAuthority: - A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1800,8 +1813,9 @@ async def sample_undelete_certificate_authority(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1924,8 +1938,9 @@ async def sample_delete_certificate_authority(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -2059,8 +2074,9 @@ async def sample_update_certificate_authority(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -2934,10 +2950,11 @@ async def sample_get_certificate_revocation_list(): Returns: google.cloud.security.privateca_v1.types.CertificateRevocationList: - A [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] corresponds to a signed X.509 certificate - Revocation List (CRL). A CRL contains the serial - numbers of certificates that should no longer be - trusted. + A + [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] + corresponds to a signed X.509 certificate Revocation + List (CRL). A CRL contains the serial numbers of + certificates that should no longer be trusted. """ # Create or coerce a protobuf request object. @@ -3178,10 +3195,11 @@ async def sample_update_certificate_revocation_list(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateRevocationList` A [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] corresponds to a signed X.509 certificate - Revocation List (CRL). A CRL contains the serial - numbers of certificates that should no longer be - trusted. + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateRevocationList` A + [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] + corresponds to a signed X.509 certificate Revocation + List (CRL). A CRL contains the serial numbers of + certificates that should no longer be trusted. """ # Create or coerce a protobuf request object. @@ -3327,7 +3345,9 @@ async def sample_create_certificate_template(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] refers to a managed template for certificate + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A + [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] + refers to a managed template for certificate issuance. """ @@ -3574,7 +3594,9 @@ async def sample_get_certificate_template(): Returns: google.cloud.security.privateca_v1.types.CertificateTemplate: - A [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] refers to a managed template for certificate + A + [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] + refers to a managed template for certificate issuance. """ @@ -3809,7 +3831,9 @@ async def sample_update_certificate_template(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] refers to a managed template for certificate + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A + [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] + refers to a managed template for certificate issuance. """ @@ -3867,6 +3891,631 @@ async def sample_update_certificate_template(): # Done; return the response. return response + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self): return self diff --git a/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py b/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py index 3174a69..bf3f53e 100644 --- a/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py +++ b/google/cloud/security/privateca_v1/services/certificate_authority_service/client.py @@ -48,6 +48,10 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore @@ -61,6 +65,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, CertificateAuthorityServiceTransport from .transports.grpc import CertificateAuthorityServiceGrpcTransport from .transports.grpc_asyncio import CertificateAuthorityServiceGrpcAsyncIOTransport +from .transports.rest import CertificateAuthorityServiceRestTransport class CertificateAuthorityServiceClientMeta(type): @@ -78,6 +83,7 @@ class CertificateAuthorityServiceClientMeta(type): _transport_registry[ "grpc_asyncio" ] = CertificateAuthorityServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CertificateAuthorityServiceRestTransport def get_transport_class( cls, @@ -640,7 +646,8 @@ def sample_create_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -750,7 +757,8 @@ def sample_get_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -857,7 +865,7 @@ def sample_list_certificates(): Returns: google.cloud.security.privateca_v1.services.certificate_authority_service.pagers.ListCertificatesPager: Response message for - [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. + [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. Iterating over this object will yield results and resolve additional pages automatically. @@ -974,7 +982,8 @@ def sample_revoke_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -1092,7 +1101,8 @@ def sample_update_certificate(): Returns: google.cloud.security.privateca_v1.types.Certificate: - A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds to a signed X.509 certificate issued by a + A [Certificate][google.cloud.security.privateca.v1.Certificate] corresponds + to a signed X.509 certificate issued by a [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. """ @@ -1222,8 +1232,9 @@ def sample_activate_certificate_authority(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1373,8 +1384,9 @@ def sample_create_certificate_authority(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1505,8 +1517,9 @@ def sample_disable_certificate_authority(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1631,8 +1644,9 @@ def sample_enable_certificate_authority(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -1868,8 +1882,9 @@ def sample_get_certificate_authority(): Returns: google.cloud.security.privateca_v1.types.CertificateAuthority: - A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -2110,8 +2125,9 @@ def sample_undelete_certificate_authority(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -2236,8 +2252,9 @@ def sample_delete_certificate_authority(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -2373,8 +2390,9 @@ def sample_update_certificate_authority(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] represents an individual Certificate Authority. - A + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateAuthority` A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] can be used to create [Certificates][google.cloud.security.privateca.v1.Certificate]. @@ -3250,10 +3268,11 @@ def sample_get_certificate_revocation_list(): Returns: google.cloud.security.privateca_v1.types.CertificateRevocationList: - A [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] corresponds to a signed X.509 certificate - Revocation List (CRL). A CRL contains the serial - numbers of certificates that should no longer be - trusted. + A + [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] + corresponds to a signed X.509 certificate Revocation + List (CRL). A CRL contains the serial numbers of + certificates that should no longer be trusted. """ # Create or coerce a protobuf request object. @@ -3498,10 +3517,11 @@ def sample_update_certificate_revocation_list(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateRevocationList` A [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] corresponds to a signed X.509 certificate - Revocation List (CRL). A CRL contains the serial - numbers of certificates that should no longer be - trusted. + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateRevocationList` A + [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] + corresponds to a signed X.509 certificate Revocation + List (CRL). A CRL contains the serial numbers of + certificates that should no longer be trusted. """ # Create or coerce a protobuf request object. @@ -3649,7 +3669,9 @@ def sample_create_certificate_template(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] refers to a managed template for certificate + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A + [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] + refers to a managed template for certificate issuance. """ @@ -3900,7 +3922,9 @@ def sample_get_certificate_template(): Returns: google.cloud.security.privateca_v1.types.CertificateTemplate: - A [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] refers to a managed template for certificate + A + [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] + refers to a managed template for certificate issuance. """ @@ -4137,7 +4161,9 @@ def sample_update_certificate_template(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] refers to a managed template for certificate + The result type for the operation will be :class:`google.cloud.security.privateca_v1.types.CertificateTemplate` A + [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] + refers to a managed template for certificate issuance. """ @@ -4210,6 +4236,631 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/__init__.py b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/__init__.py index a2ba1e2..930dac8 100644 --- a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/__init__.py +++ b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/__init__.py @@ -19,6 +19,10 @@ from .base import CertificateAuthorityServiceTransport from .grpc import CertificateAuthorityServiceGrpcTransport from .grpc_asyncio import CertificateAuthorityServiceGrpcAsyncIOTransport +from .rest import ( + CertificateAuthorityServiceRestInterceptor, + CertificateAuthorityServiceRestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -26,9 +30,12 @@ ) # type: Dict[str, Type[CertificateAuthorityServiceTransport]] _transport_registry["grpc"] = CertificateAuthorityServiceGrpcTransport _transport_registry["grpc_asyncio"] = CertificateAuthorityServiceGrpcAsyncIOTransport +_transport_registry["rest"] = CertificateAuthorityServiceRestTransport __all__ = ( "CertificateAuthorityServiceTransport", "CertificateAuthorityServiceGrpcTransport", "CertificateAuthorityServiceGrpcAsyncIOTransport", + "CertificateAuthorityServiceRestTransport", + "CertificateAuthorityServiceRestInterceptor", ) diff --git a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py index e52f7ae..e115633 100644 --- a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py +++ b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/base.py @@ -22,6 +22,9 @@ from google.api_core import retry as retries import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account # type: ignore @@ -564,6 +567,90 @@ def update_certificate_template( ]: raise NotImplementedError() + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc.py b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc.py index a944ac4..9736adf 100644 --- a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc.py +++ b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc.py @@ -20,6 +20,9 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore @@ -1107,6 +1110,192 @@ def update_certificate_template( def close(self): self.grpc_channel.close() + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + @property def kind(self) -> str: return "grpc" diff --git a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py index 0b8d3c5..d3643b2 100644 --- a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py +++ b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/grpc_asyncio.py @@ -19,6 +19,9 @@ from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -1132,5 +1135,191 @@ def update_certificate_template( def close(self): return self.grpc_channel.close() + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + __all__ = ("CertificateAuthorityServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py new file mode 100644 index 0000000..3ce81d6 --- /dev/null +++ b/google/cloud/security/privateca_v1/services/certificate_authority_service/transports/rest.py @@ -0,0 +1,5065 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.security.privateca_v1.types import resources, service + +from .base import CertificateAuthorityServiceTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CertificateAuthorityServiceRestInterceptor: + """Interceptor for CertificateAuthorityService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CertificateAuthorityServiceRestTransport. + + .. code-block:: python + class MyCustomCertificateAuthorityServiceInterceptor(CertificateAuthorityServiceRestInterceptor): + def pre_activate_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_activate_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_ca_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_ca_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_ca_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_ca_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_certificate_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_certificate_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_disable_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_enable_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_ca_certs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_ca_certs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_certificate_authority_csr(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_certificate_authority_csr(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ca_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ca_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_revocation_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_revocation_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_ca_pools(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_ca_pools(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_authorities(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_authorities(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_revocation_lists(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_revocation_lists(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_templates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_templates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_revoke_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_revoke_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_ca_pool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_ca_pool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate_revocation_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate_revocation_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate_template(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CertificateAuthorityServiceRestTransport(interceptor=MyCustomCertificateAuthorityServiceInterceptor()) + client = CertificateAuthorityServiceClient(transport=transport) + + + """ + + def pre_activate_certificate_authority( + self, + request: service.ActivateCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ActivateCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for activate_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_activate_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for activate_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_create_ca_pool( + self, request: service.CreateCaPoolRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.CreateCaPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_ca_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_create_ca_pool( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_ca_pool + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_create_certificate( + self, + request: service.CreateCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_create_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for create_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_create_certificate_authority( + self, + request: service.CreateCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_create_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_create_certificate_template( + self, + request: service.CreateCertificateTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateCertificateTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_certificate_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_create_certificate_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_certificate_template + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_delete_ca_pool( + self, request: service.DeleteCaPoolRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.DeleteCaPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_ca_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_delete_ca_pool( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_ca_pool + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_delete_certificate_authority( + self, + request: service.DeleteCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DeleteCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_delete_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_delete_certificate_template( + self, + request: service.DeleteCertificateTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DeleteCertificateTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_certificate_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_delete_certificate_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_certificate_template + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_disable_certificate_authority( + self, + request: service.DisableCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DisableCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for disable_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_disable_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for disable_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_enable_certificate_authority( + self, + request: service.EnableCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.EnableCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for enable_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_enable_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for enable_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_fetch_ca_certs( + self, request: service.FetchCaCertsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.FetchCaCertsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for fetch_ca_certs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_fetch_ca_certs( + self, response: service.FetchCaCertsResponse + ) -> service.FetchCaCertsResponse: + """Post-rpc interceptor for fetch_ca_certs + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_fetch_certificate_authority_csr( + self, + request: service.FetchCertificateAuthorityCsrRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.FetchCertificateAuthorityCsrRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for fetch_certificate_authority_csr + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_fetch_certificate_authority_csr( + self, response: service.FetchCertificateAuthorityCsrResponse + ) -> service.FetchCertificateAuthorityCsrResponse: + """Post-rpc interceptor for fetch_certificate_authority_csr + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_ca_pool( + self, request: service.GetCaPoolRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetCaPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_ca_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_ca_pool(self, response: resources.CaPool) -> resources.CaPool: + """Post-rpc interceptor for get_ca_pool + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_certificate( + self, + request: service.GetCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for get_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_authority( + self, + request: service.GetCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_certificate_authority( + self, response: resources.CertificateAuthority + ) -> resources.CertificateAuthority: + """Post-rpc interceptor for get_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_revocation_list( + self, + request: service.GetCertificateRevocationListRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCertificateRevocationListRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate_revocation_list + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_certificate_revocation_list( + self, response: resources.CertificateRevocationList + ) -> resources.CertificateRevocationList: + """Post-rpc interceptor for get_certificate_revocation_list + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_template( + self, + request: service.GetCertificateTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCertificateTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_certificate_template( + self, response: resources.CertificateTemplate + ) -> resources.CertificateTemplate: + """Post-rpc interceptor for get_certificate_template + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_ca_pools( + self, request: service.ListCaPoolsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListCaPoolsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_ca_pools + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_ca_pools( + self, response: service.ListCaPoolsResponse + ) -> service.ListCaPoolsResponse: + """Post-rpc interceptor for list_ca_pools + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_authorities( + self, + request: service.ListCertificateAuthoritiesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListCertificateAuthoritiesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_certificate_authorities + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_certificate_authorities( + self, response: service.ListCertificateAuthoritiesResponse + ) -> service.ListCertificateAuthoritiesResponse: + """Post-rpc interceptor for list_certificate_authorities + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_revocation_lists( + self, + request: service.ListCertificateRevocationListsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + service.ListCertificateRevocationListsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_certificate_revocation_lists + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_certificate_revocation_lists( + self, response: service.ListCertificateRevocationListsResponse + ) -> service.ListCertificateRevocationListsResponse: + """Post-rpc interceptor for list_certificate_revocation_lists + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_certificates( + self, + request: service.ListCertificatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListCertificatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_certificates + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_certificates( + self, response: service.ListCertificatesResponse + ) -> service.ListCertificatesResponse: + """Post-rpc interceptor for list_certificates + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_templates( + self, + request: service.ListCertificateTemplatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListCertificateTemplatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_certificate_templates + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_certificate_templates( + self, response: service.ListCertificateTemplatesResponse + ) -> service.ListCertificateTemplatesResponse: + """Post-rpc interceptor for list_certificate_templates + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_revoke_certificate( + self, + request: service.RevokeCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.RevokeCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for revoke_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_revoke_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for revoke_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_undelete_certificate_authority( + self, + request: service.UndeleteCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UndeleteCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for undelete_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_undelete_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for undelete_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_ca_pool( + self, request: service.UpdateCaPoolRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.UpdateCaPoolRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_ca_pool + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_ca_pool( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_ca_pool + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_certificate( + self, + request: service.UpdateCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for update_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_certificate_authority( + self, + request: service.UpdateCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_certificate_revocation_list( + self, + request: service.UpdateCertificateRevocationListRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + service.UpdateCertificateRevocationListRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_certificate_revocation_list + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_certificate_revocation_list( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate_revocation_list + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_certificate_template( + self, + request: service.UpdateCertificateTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCertificateTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_certificate_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_certificate_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate_template + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CertificateAuthorityServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CertificateAuthorityServiceRestInterceptor + + +class CertificateAuthorityServiceRestTransport(CertificateAuthorityServiceTransport): + """REST backend transport for CertificateAuthorityService. + + [Certificate Authority + Service][google.cloud.security.privateca.v1.CertificateAuthorityService] + manages private certificate authorities and issued certificates. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "privateca.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CertificateAuthorityServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CertificateAuthorityServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _ActivateCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ActivateCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ActivateCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the activate certificate + authority method over HTTP. + + Args: + request (~.service.ActivateCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.ActivateCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.ActivateCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:activate", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_activate_certificate_authority( + request, metadata + ) + pb_request = service.ActivateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_activate_certificate_authority(resp) + return resp + + class _CreateCaPool(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("CreateCaPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "caPoolId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCaPoolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create ca pool method over HTTP. + + Args: + request (~.service.CreateCaPoolRequest): + The request object. Request message for + [CertificateAuthorityService.CreateCaPool][google.cloud.security.privateca.v1.CertificateAuthorityService.CreateCaPool]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/caPools", + "body": "ca_pool", + }, + ] + request, metadata = self._interceptor.pre_create_ca_pool(request, metadata) + pb_request = service.CreateCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_ca_pool(resp) + return resp + + class _CreateCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("CreateCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the create certificate method over HTTP. + + Args: + request (~.service.CreateCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.CreateCertificate][google.cloud.security.privateca.v1.CertificateAuthorityService.CreateCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificates", + "body": "certificate", + }, + ] + request, metadata = self._interceptor.pre_create_certificate( + request, metadata + ) + pb_request = service.CreateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate(resp) + return resp + + class _CreateCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("CreateCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "certificateAuthorityId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create certificate + authority method over HTTP. + + Args: + request (~.service.CreateCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.CreateCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.CreateCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities", + "body": "certificate_authority", + }, + ] + request, metadata = self._interceptor.pre_create_certificate_authority( + request, metadata + ) + pb_request = service.CreateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate_authority(resp) + return resp + + class _CreateCertificateTemplate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("CreateCertificateTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "certificateTemplateId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCertificateTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create certificate + template method over HTTP. + + Args: + request (~.service.CreateCertificateTemplateRequest): + The request object. Request message for + [CertificateAuthorityService.CreateCertificateTemplate][google.cloud.security.privateca.v1.CertificateAuthorityService.CreateCertificateTemplate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/certificateTemplates", + "body": "certificate_template", + }, + ] + request, metadata = self._interceptor.pre_create_certificate_template( + request, metadata + ) + pb_request = service.CreateCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate_template(resp) + return resp + + class _DeleteCaPool(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("DeleteCaPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.DeleteCaPoolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete ca pool method over HTTP. + + Args: + request (~.service.DeleteCaPoolRequest): + The request object. Request message for + [CertificateAuthorityService.DeleteCaPool][google.cloud.security.privateca.v1.CertificateAuthorityService.DeleteCaPool]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/caPools/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_ca_pool(request, metadata) + pb_request = service.DeleteCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_ca_pool(resp) + return resp + + class _DeleteCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("DeleteCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.DeleteCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete certificate + authority method over HTTP. + + Args: + request (~.service.DeleteCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.DeleteCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.DeleteCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_certificate_authority( + request, metadata + ) + pb_request = service.DeleteCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_certificate_authority(resp) + return resp + + class _DeleteCertificateTemplate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("DeleteCertificateTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.DeleteCertificateTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete certificate + template method over HTTP. + + Args: + request (~.service.DeleteCertificateTemplateRequest): + The request object. Request message for + [CertificateAuthorityService.DeleteCertificateTemplate][google.cloud.security.privateca.v1.CertificateAuthorityService.DeleteCertificateTemplate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/certificateTemplates/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_certificate_template( + request, metadata + ) + pb_request = service.DeleteCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_certificate_template(resp) + return resp + + class _DisableCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("DisableCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.DisableCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the disable certificate + authority method over HTTP. + + Args: + request (~.service.DisableCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.DisableCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.DisableCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:disable", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_disable_certificate_authority( + request, metadata + ) + pb_request = service.DisableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_disable_certificate_authority(resp) + return resp + + class _EnableCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("EnableCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.EnableCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the enable certificate + authority method over HTTP. + + Args: + request (~.service.EnableCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.EnableCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.EnableCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:enable", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_enable_certificate_authority( + request, metadata + ) + pb_request = service.EnableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_enable_certificate_authority(resp) + return resp + + class _FetchCaCerts(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("FetchCaCerts") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.FetchCaCertsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.FetchCaCertsResponse: + r"""Call the fetch ca certs method over HTTP. + + Args: + request (~.service.FetchCaCertsRequest): + The request object. Request message for + [CertificateAuthorityService.FetchCaCerts][google.cloud.security.privateca.v1.CertificateAuthorityService.FetchCaCerts]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.FetchCaCertsResponse: + Response message for + [CertificateAuthorityService.FetchCaCerts][google.cloud.security.privateca.v1.CertificateAuthorityService.FetchCaCerts]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{ca_pool=projects/*/locations/*/caPools/*}:fetchCaCerts", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_fetch_ca_certs(request, metadata) + pb_request = service.FetchCaCertsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.FetchCaCertsResponse() + pb_resp = service.FetchCaCertsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_ca_certs(resp) + return resp + + class _FetchCertificateAuthorityCsr(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("FetchCertificateAuthorityCsr") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.FetchCertificateAuthorityCsrRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.FetchCertificateAuthorityCsrResponse: + r"""Call the fetch certificate + authority csr method over HTTP. + + Args: + request (~.service.FetchCertificateAuthorityCsrRequest): + The request object. Request message for + [CertificateAuthorityService.FetchCertificateAuthorityCsr][google.cloud.security.privateca.v1.CertificateAuthorityService.FetchCertificateAuthorityCsr]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.FetchCertificateAuthorityCsrResponse: + Response message for + [CertificateAuthorityService.FetchCertificateAuthorityCsr][google.cloud.security.privateca.v1.CertificateAuthorityService.FetchCertificateAuthorityCsr]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:fetch", + }, + ] + request, metadata = self._interceptor.pre_fetch_certificate_authority_csr( + request, metadata + ) + pb_request = service.FetchCertificateAuthorityCsrRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.FetchCertificateAuthorityCsrResponse() + pb_resp = service.FetchCertificateAuthorityCsrResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_certificate_authority_csr(resp) + return resp + + class _GetCaPool(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCaPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCaPoolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CaPool: + r"""Call the get ca pool method over HTTP. + + Args: + request (~.service.GetCaPoolRequest): + The request object. Request message for + [CertificateAuthorityService.GetCaPool][google.cloud.security.privateca.v1.CertificateAuthorityService.GetCaPool]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CaPool: + A [CaPool][google.cloud.security.privateca.v1.CaPool] + represents a group of + [CertificateAuthorities][google.cloud.security.privateca.v1.CertificateAuthority] + that form a trust anchor. A + [CaPool][google.cloud.security.privateca.v1.CaPool] can + be used to manage issuance policies for one or more + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + resources and to rotate CA certificates in and out of + the trust anchor. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*}", + }, + ] + request, metadata = self._interceptor.pre_get_ca_pool(request, metadata) + pb_request = service.GetCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CaPool() + pb_resp = resources.CaPool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_ca_pool(resp) + return resp + + class _GetCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the get certificate method over HTTP. + + Args: + request (~.service.GetCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.GetCertificate][google.cloud.security.privateca.v1.CertificateAuthorityService.GetCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificates/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate(request, metadata) + pb_request = service.GetCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate(resp) + return resp + + class _GetCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CertificateAuthority: + r"""Call the get certificate authority method over HTTP. + + Args: + request (~.service.GetCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.GetCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.GetCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CertificateAuthority: + A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + represents an individual Certificate Authority. A + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority] + can be used to create + [Certificates][google.cloud.security.privateca.v1.Certificate]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_authority( + request, metadata + ) + pb_request = service.GetCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CertificateAuthority() + pb_resp = resources.CertificateAuthority.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_authority(resp) + return resp + + class _GetCertificateRevocationList(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCertificateRevocationList") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCertificateRevocationListRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CertificateRevocationList: + r"""Call the get certificate + revocation list method over HTTP. + + Args: + request (~.service.GetCertificateRevocationListRequest): + The request object. Request message for + [CertificateAuthorityService.GetCertificateRevocationList][google.cloud.security.privateca.v1.CertificateAuthorityService.GetCertificateRevocationList]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CertificateRevocationList: + A + [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] + corresponds to a signed X.509 certificate Revocation + List (CRL). A CRL contains the serial numbers of + certificates that should no longer be trusted. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_revocation_list( + request, metadata + ) + pb_request = service.GetCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CertificateRevocationList() + pb_resp = resources.CertificateRevocationList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_revocation_list(resp) + return resp + + class _GetCertificateTemplate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCertificateTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCertificateTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CertificateTemplate: + r"""Call the get certificate template method over HTTP. + + Args: + request (~.service.GetCertificateTemplateRequest): + The request object. Request message for + [CertificateAuthorityService.GetCertificateTemplate][google.cloud.security.privateca.v1.CertificateAuthorityService.GetCertificateTemplate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CertificateTemplate: + A + [CertificateTemplate][google.cloud.security.privateca.v1.CertificateTemplate] + refers to a managed template for certificate issuance. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/certificateTemplates/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_template( + request, metadata + ) + pb_request = service.GetCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CertificateTemplate() + pb_resp = resources.CertificateTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_template(resp) + return resp + + class _ListCaPools(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCaPools") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCaPoolsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCaPoolsResponse: + r"""Call the list ca pools method over HTTP. + + Args: + request (~.service.ListCaPoolsRequest): + The request object. Request message for + [CertificateAuthorityService.ListCaPools][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCaPools]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCaPoolsResponse: + Response message for + [CertificateAuthorityService.ListCaPools][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCaPools]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/caPools", + }, + ] + request, metadata = self._interceptor.pre_list_ca_pools(request, metadata) + pb_request = service.ListCaPoolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCaPoolsResponse() + pb_resp = service.ListCaPoolsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_ca_pools(resp) + return resp + + class _ListCertificateAuthorities(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCertificateAuthorities") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCertificateAuthoritiesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCertificateAuthoritiesResponse: + r"""Call the list certificate + authorities method over HTTP. + + Args: + request (~.service.ListCertificateAuthoritiesRequest): + The request object. Request message for + [CertificateAuthorityService.ListCertificateAuthorities][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificateAuthorities]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCertificateAuthoritiesResponse: + Response message for + [CertificateAuthorityService.ListCertificateAuthorities][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificateAuthorities]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_authorities( + request, metadata + ) + pb_request = service.ListCertificateAuthoritiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCertificateAuthoritiesResponse() + pb_resp = service.ListCertificateAuthoritiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_authorities(resp) + return resp + + class _ListCertificateRevocationLists(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCertificateRevocationLists") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCertificateRevocationListsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCertificateRevocationListsResponse: + r"""Call the list certificate + revocation lists method over HTTP. + + Args: + request (~.service.ListCertificateRevocationListsRequest): + The request object. Request message for + [CertificateAuthorityService.ListCertificateRevocationLists][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificateRevocationLists]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCertificateRevocationListsResponse: + Response message for + [CertificateAuthorityService.ListCertificateRevocationLists][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificateRevocationLists]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*/certificateAuthorities/*}/certificateRevocationLists", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_revocation_lists( + request, metadata + ) + pb_request = service.ListCertificateRevocationListsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCertificateRevocationListsResponse() + pb_resp = service.ListCertificateRevocationListsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_revocation_lists(resp) + return resp + + class _ListCertificates(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCertificates") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCertificatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCertificatesResponse: + r"""Call the list certificates method over HTTP. + + Args: + request (~.service.ListCertificatesRequest): + The request object. Request message for + [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCertificatesResponse: + Response message for + [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificates]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/caPools/*}/certificates", + }, + ] + request, metadata = self._interceptor.pre_list_certificates( + request, metadata + ) + pb_request = service.ListCertificatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCertificatesResponse() + pb_resp = service.ListCertificatesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificates(resp) + return resp + + class _ListCertificateTemplates(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCertificateTemplates") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCertificateTemplatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCertificateTemplatesResponse: + r"""Call the list certificate + templates method over HTTP. + + Args: + request (~.service.ListCertificateTemplatesRequest): + The request object. Request message for + [CertificateAuthorityService.ListCertificateTemplates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificateTemplates]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCertificateTemplatesResponse: + Response message for + [CertificateAuthorityService.ListCertificateTemplates][google.cloud.security.privateca.v1.CertificateAuthorityService.ListCertificateTemplates]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/certificateTemplates", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_templates( + request, metadata + ) + pb_request = service.ListCertificateTemplatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCertificateTemplatesResponse() + pb_resp = service.ListCertificateTemplatesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_templates(resp) + return resp + + class _RevokeCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("RevokeCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.RevokeCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the revoke certificate method over HTTP. + + Args: + request (~.service.RevokeCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.RevokeCertificate][google.cloud.security.privateca.v1.CertificateAuthorityService.RevokeCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificates/*}:revoke", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_revoke_certificate( + request, metadata + ) + pb_request = service.RevokeCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_revoke_certificate(resp) + return resp + + class _UndeleteCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UndeleteCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UndeleteCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the undelete certificate + authority method over HTTP. + + Args: + request (~.service.UndeleteCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.UndeleteCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.UndeleteCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:undelete", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_undelete_certificate_authority( + request, metadata + ) + pb_request = service.UndeleteCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undelete_certificate_authority(resp) + return resp + + class _UpdateCaPool(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCaPool") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCaPoolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update ca pool method over HTTP. + + Args: + request (~.service.UpdateCaPoolRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCaPool][google.cloud.security.privateca.v1.CertificateAuthorityService.UpdateCaPool]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{ca_pool.name=projects/*/locations/*/caPools/*}", + "body": "ca_pool", + }, + ] + request, metadata = self._interceptor.pre_update_ca_pool(request, metadata) + pb_request = service.UpdateCaPoolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_ca_pool(resp) + return resp + + class _UpdateCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the update certificate method over HTTP. + + Args: + request (~.service.UpdateCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCertificate][google.cloud.security.privateca.v1.CertificateAuthorityService.UpdateCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate.name=projects/*/locations/*/caPools/*/certificates/*}", + "body": "certificate", + }, + ] + request, metadata = self._interceptor.pre_update_certificate( + request, metadata + ) + pb_request = service.UpdateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate(resp) + return resp + + class _UpdateCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate + authority method over HTTP. + + Args: + request (~.service.UpdateCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCertificateAuthority][google.cloud.security.privateca.v1.CertificateAuthorityService.UpdateCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_authority.name=projects/*/locations/*/caPools/*/certificateAuthorities/*}", + "body": "certificate_authority", + }, + ] + request, metadata = self._interceptor.pre_update_certificate_authority( + request, metadata + ) + pb_request = service.UpdateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate_authority(resp) + return resp + + class _UpdateCertificateRevocationList(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCertificateRevocationList") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCertificateRevocationListRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate + revocation list method over HTTP. + + Args: + request (~.service.UpdateCertificateRevocationListRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCertificateRevocationList][google.cloud.security.privateca.v1.CertificateAuthorityService.UpdateCertificateRevocationList]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_revocation_list.name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}", + "body": "certificate_revocation_list", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_update_certificate_revocation_list( + request, metadata + ) + pb_request = service.UpdateCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate_revocation_list(resp) + return resp + + class _UpdateCertificateTemplate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCertificateTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCertificateTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate + template method over HTTP. + + Args: + request (~.service.UpdateCertificateTemplateRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCertificateTemplate][google.cloud.security.privateca.v1.CertificateAuthorityService.UpdateCertificateTemplate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{certificate_template.name=projects/*/locations/*/certificateTemplates/*}", + "body": "certificate_template", + }, + ] + request, metadata = self._interceptor.pre_update_certificate_template( + request, metadata + ) + pb_request = service.UpdateCertificateTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate_template(resp) + return resp + + @property + def activate_certificate_authority( + self, + ) -> Callable[ + [service.ActivateCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ActivateCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_ca_pool( + self, + ) -> Callable[[service.CreateCaPoolRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCaPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate( + self, + ) -> Callable[[service.CreateCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate_authority( + self, + ) -> Callable[ + [service.CreateCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate_template( + self, + ) -> Callable[[service.CreateCertificateTemplateRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificateTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_ca_pool( + self, + ) -> Callable[[service.DeleteCaPoolRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCaPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_certificate_authority( + self, + ) -> Callable[ + [service.DeleteCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_certificate_template( + self, + ) -> Callable[[service.DeleteCertificateTemplateRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCertificateTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def disable_certificate_authority( + self, + ) -> Callable[ + [service.DisableCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DisableCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def enable_certificate_authority( + self, + ) -> Callable[ + [service.EnableCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EnableCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_ca_certs( + self, + ) -> Callable[[service.FetchCaCertsRequest], service.FetchCaCertsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchCaCerts(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_certificate_authority_csr( + self, + ) -> Callable[ + [service.FetchCertificateAuthorityCsrRequest], + service.FetchCertificateAuthorityCsrResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchCertificateAuthorityCsr(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ca_pool(self) -> Callable[[service.GetCaPoolRequest], resources.CaPool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCaPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate( + self, + ) -> Callable[[service.GetCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_authority( + self, + ) -> Callable[ + [service.GetCertificateAuthorityRequest], resources.CertificateAuthority + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_revocation_list( + self, + ) -> Callable[ + [service.GetCertificateRevocationListRequest], + resources.CertificateRevocationList, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateRevocationList(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_template( + self, + ) -> Callable[ + [service.GetCertificateTemplateRequest], resources.CertificateTemplate + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_ca_pools( + self, + ) -> Callable[[service.ListCaPoolsRequest], service.ListCaPoolsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCaPools(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_authorities( + self, + ) -> Callable[ + [service.ListCertificateAuthoritiesRequest], + service.ListCertificateAuthoritiesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateAuthorities(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_revocation_lists( + self, + ) -> Callable[ + [service.ListCertificateRevocationListsRequest], + service.ListCertificateRevocationListsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateRevocationLists(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificates( + self, + ) -> Callable[[service.ListCertificatesRequest], service.ListCertificatesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificates(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_templates( + self, + ) -> Callable[ + [service.ListCertificateTemplatesRequest], + service.ListCertificateTemplatesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateTemplates(self._session, self._host, self._interceptor) # type: ignore + + @property + def revoke_certificate( + self, + ) -> Callable[[service.RevokeCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RevokeCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def undelete_certificate_authority( + self, + ) -> Callable[ + [service.UndeleteCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeleteCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_ca_pool( + self, + ) -> Callable[[service.UpdateCaPoolRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCaPool(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate( + self, + ) -> Callable[[service.UpdateCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate_authority( + self, + ) -> Callable[ + [service.UpdateCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate_revocation_list( + self, + ) -> Callable[ + [service.UpdateCertificateRevocationListRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificateRevocationList(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate_template( + self, + ) -> Callable[[service.UpdateCertificateTemplateRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificateTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:getIamPolicy", + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:setIamPolicy", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/certificateTemplates/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}:testIamPermissions", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request["body"])) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(CertificateAuthorityServiceRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CertificateAuthorityServiceRestTransport",) diff --git a/google/cloud/security/privateca_v1/types/resources.py b/google/cloud/security/privateca_v1/types/resources.py index b83160b..5bfe1e6 100644 --- a/google/cloud/security/privateca_v1/types/resources.py +++ b/google/cloud/security/privateca_v1/types/resources.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import duration_pb2 # type: ignore @@ -1325,6 +1327,9 @@ class X509Parameters(proto.Message): Protocol (OCSP) endpoint addresses that appear in the "Authority Information Access" extension in the certificate. + name_constraints (google.cloud.security.privateca_v1.types.X509Parameters.NameConstraints): + Optional. Describes the X.509 name + constraints extension. additional_extensions (MutableSequence[google.cloud.security.privateca_v1.types.X509Extension]): Optional. Describes custom X.509 extensions. """ @@ -1365,6 +1370,99 @@ class CaOptions(proto.Message): optional=True, ) + class NameConstraints(proto.Message): + r"""Describes the X.509 name constraints extension, per + https://tools.ietf.org/html/rfc5280#section-4.2.1.10 + + Attributes: + critical (bool): + Indicates whether or not the name constraints + are marked critical. + permitted_dns_names (MutableSequence[str]): + Contains permitted DNS names. Any DNS name that can be + constructed by simply adding zero or more labels to the + left-hand side of the name satisfies the name constraint. + For example, ``example.com``, ``www.example.com``, + ``www.sub.example.com`` would satisfy ``example.com`` while + ``example1.com`` does not. + excluded_dns_names (MutableSequence[str]): + Contains excluded DNS names. Any DNS name that can be + constructed by simply adding zero or more labels to the + left-hand side of the name satisfies the name constraint. + For example, ``example.com``, ``www.example.com``, + ``www.sub.example.com`` would satisfy ``example.com`` while + ``example1.com`` does not. + permitted_ip_ranges (MutableSequence[str]): + Contains the permitted IP ranges. For IPv4 + addresses, the ranges are expressed using CIDR + notation as specified in RFC 4632. For IPv6 + addresses, the ranges are expressed in similar + encoding as IPv4 addresses. + excluded_ip_ranges (MutableSequence[str]): + Contains the excluded IP ranges. For IPv4 + addresses, the ranges are expressed using CIDR + notation as specified in RFC 4632. For IPv6 + addresses, the ranges are expressed in similar + encoding as IPv4 addresses. + permitted_email_addresses (MutableSequence[str]): + Contains the permitted email addresses. The value can be a + particular email address, a hostname to indicate all email + addresses on that host or a domain with a leading period + (e.g. ``.example.com``) to indicate all email addresses in + that domain. + excluded_email_addresses (MutableSequence[str]): + Contains the excluded email addresses. The value can be a + particular email address, a hostname to indicate all email + addresses on that host or a domain with a leading period + (e.g. ``.example.com``) to indicate all email addresses in + that domain. + permitted_uris (MutableSequence[str]): + Contains the permitted URIs that apply to the host part of + the name. The value can be a hostname or a domain with a + leading period (like ``.example.com``) + excluded_uris (MutableSequence[str]): + Contains the excluded URIs that apply to the host part of + the name. The value can be a hostname or a domain with a + leading period (like ``.example.com``) + """ + + critical: bool = proto.Field( + proto.BOOL, + number=1, + ) + permitted_dns_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + excluded_dns_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + permitted_ip_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + excluded_ip_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + permitted_email_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + excluded_email_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + permitted_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + excluded_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + key_usage: "KeyUsage" = proto.Field( proto.MESSAGE, number=1, @@ -1384,6 +1482,11 @@ class CaOptions(proto.Message): proto.STRING, number=4, ) + name_constraints: NameConstraints = proto.Field( + proto.MESSAGE, + number=6, + message=NameConstraints, + ) additional_extensions: MutableSequence["X509Extension"] = proto.RepeatedField( proto.MESSAGE, number=5, @@ -2166,6 +2269,10 @@ class KnownCertificateExtension(proto.Enum): This corresponds to the [X509Parameters.aia_ocsp_servers][google.cloud.security.privateca.v1.X509Parameters.aia_ocsp_servers] field. + NAME_CONSTRAINTS (6): + Refers to Name Constraints extension as described in `RFC + 5280 section + 4.2.1.10 `__ """ KNOWN_CERTIFICATE_EXTENSION_UNSPECIFIED = 0 BASE_KEY_USAGE = 1 @@ -2173,6 +2280,7 @@ class KnownCertificateExtension(proto.Enum): CA_OPTIONS = 3 POLICY_IDS = 4 AIA_OCSP_SERVERS = 5 + NAME_CONSTRAINTS = 6 known_extensions: MutableSequence[KnownCertificateExtension] = proto.RepeatedField( proto.ENUM, diff --git a/google/cloud/security/privateca_v1/types/service.py b/google/cloud/security/privateca_v1/types/service.py index 70de105..d9cc0fe 100644 --- a/google/cloud/security/privateca_v1/types/service.py +++ b/google/cloud/security/privateca_v1/types/service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import field_mask_pb2 # type: ignore @@ -304,11 +306,11 @@ class RevokeCertificateRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -352,11 +354,11 @@ class UpdateCertificateRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -406,11 +408,11 @@ class ActivateCertificateAuthorityRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -464,11 +466,11 @@ class CreateCertificateAuthorityRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -514,11 +516,11 @@ class DisableCertificateAuthorityRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -555,11 +557,11 @@ class EnableCertificateAuthorityRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -740,11 +742,11 @@ class UndeleteCertificateAuthorityRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -781,11 +783,11 @@ class DeleteCertificateAuthorityRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -844,11 +846,11 @@ class UpdateCertificateAuthorityRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -897,11 +899,11 @@ class CreateCaPoolRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -949,11 +951,11 @@ class UpdateCaPoolRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -995,11 +997,11 @@ class DeleteCaPoolRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -1035,11 +1037,11 @@ class FetchCaCertsRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -1327,11 +1329,11 @@ class UpdateCertificateRevocationListRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -1381,11 +1383,11 @@ class CreateCertificateTemplateRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -1431,11 +1433,11 @@ class DeleteCertificateTemplateRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the @@ -1583,11 +1585,11 @@ class UpdateCertificateTemplateRequest(proto.Message): minutes since the first request. For example, consider a situation where you make - an initial request and t he request times out. - If you make the request again with the same - request ID, the server can check if original - operation with the same request ID was received, - and if so, will ignore the second request. This + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the diff --git a/google/cloud/security/privateca_v1beta1/gapic_metadata.json b/google/cloud/security/privateca_v1beta1/gapic_metadata.json index 3406d51..ee3a315 100644 --- a/google/cloud/security/privateca_v1beta1/gapic_metadata.json +++ b/google/cloud/security/privateca_v1beta1/gapic_metadata.json @@ -216,6 +216,111 @@ ] } } + }, + "rest": { + "libraryClient": "CertificateAuthorityServiceClient", + "rpcs": { + "ActivateCertificateAuthority": { + "methods": [ + "activate_certificate_authority" + ] + }, + "CreateCertificate": { + "methods": [ + "create_certificate" + ] + }, + "CreateCertificateAuthority": { + "methods": [ + "create_certificate_authority" + ] + }, + "DisableCertificateAuthority": { + "methods": [ + "disable_certificate_authority" + ] + }, + "EnableCertificateAuthority": { + "methods": [ + "enable_certificate_authority" + ] + }, + "FetchCertificateAuthorityCsr": { + "methods": [ + "fetch_certificate_authority_csr" + ] + }, + "GetCertificate": { + "methods": [ + "get_certificate" + ] + }, + "GetCertificateAuthority": { + "methods": [ + "get_certificate_authority" + ] + }, + "GetCertificateRevocationList": { + "methods": [ + "get_certificate_revocation_list" + ] + }, + "GetReusableConfig": { + "methods": [ + "get_reusable_config" + ] + }, + "ListCertificateAuthorities": { + "methods": [ + "list_certificate_authorities" + ] + }, + "ListCertificateRevocationLists": { + "methods": [ + "list_certificate_revocation_lists" + ] + }, + "ListCertificates": { + "methods": [ + "list_certificates" + ] + }, + "ListReusableConfigs": { + "methods": [ + "list_reusable_configs" + ] + }, + "RestoreCertificateAuthority": { + "methods": [ + "restore_certificate_authority" + ] + }, + "RevokeCertificate": { + "methods": [ + "revoke_certificate" + ] + }, + "ScheduleDeleteCertificateAuthority": { + "methods": [ + "schedule_delete_certificate_authority" + ] + }, + "UpdateCertificate": { + "methods": [ + "update_certificate" + ] + }, + "UpdateCertificateAuthority": { + "methods": [ + "update_certificate_authority" + ] + }, + "UpdateCertificateRevocationList": { + "methods": [ + "update_certificate_revocation_list" + ] + } + } } } } diff --git a/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/client.py b/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/client.py index 6f11e10..7380904 100644 --- a/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/client.py +++ b/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/client.py @@ -60,6 +60,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, CertificateAuthorityServiceTransport from .transports.grpc import CertificateAuthorityServiceGrpcTransport from .transports.grpc_asyncio import CertificateAuthorityServiceGrpcAsyncIOTransport +from .transports.rest import CertificateAuthorityServiceRestTransport class CertificateAuthorityServiceClientMeta(type): @@ -77,6 +78,7 @@ class CertificateAuthorityServiceClientMeta(type): _transport_registry[ "grpc_asyncio" ] = CertificateAuthorityServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CertificateAuthorityServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/__init__.py b/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/__init__.py index a2ba1e2..930dac8 100644 --- a/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/__init__.py +++ b/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/__init__.py @@ -19,6 +19,10 @@ from .base import CertificateAuthorityServiceTransport from .grpc import CertificateAuthorityServiceGrpcTransport from .grpc_asyncio import CertificateAuthorityServiceGrpcAsyncIOTransport +from .rest import ( + CertificateAuthorityServiceRestInterceptor, + CertificateAuthorityServiceRestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -26,9 +30,12 @@ ) # type: Dict[str, Type[CertificateAuthorityServiceTransport]] _transport_registry["grpc"] = CertificateAuthorityServiceGrpcTransport _transport_registry["grpc_asyncio"] = CertificateAuthorityServiceGrpcAsyncIOTransport +_transport_registry["rest"] = CertificateAuthorityServiceRestTransport __all__ = ( "CertificateAuthorityServiceTransport", "CertificateAuthorityServiceGrpcTransport", "CertificateAuthorityServiceGrpcAsyncIOTransport", + "CertificateAuthorityServiceRestTransport", + "CertificateAuthorityServiceRestInterceptor", ) diff --git a/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py b/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py new file mode 100644 index 0000000..acf5ab2 --- /dev/null +++ b/google/cloud/security/privateca_v1beta1/services/certificate_authority_service/transports/rest.py @@ -0,0 +1,3035 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.security.privateca_v1beta1.types import resources, service + +from .base import CertificateAuthorityServiceTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CertificateAuthorityServiceRestInterceptor: + """Interceptor for CertificateAuthorityService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CertificateAuthorityServiceRestTransport. + + .. code-block:: python + class MyCustomCertificateAuthorityServiceInterceptor(CertificateAuthorityServiceRestInterceptor): + def pre_activate_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_activate_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_disable_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_enable_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_certificate_authority_csr(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_certificate_authority_csr(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_certificate_revocation_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_certificate_revocation_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_reusable_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_reusable_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_authorities(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_authorities(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificate_revocation_lists(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificate_revocation_lists(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_certificates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_certificates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_reusable_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_reusable_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_revoke_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_revoke_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_schedule_delete_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_schedule_delete_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate_authority(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate_authority(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_certificate_revocation_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_certificate_revocation_list(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CertificateAuthorityServiceRestTransport(interceptor=MyCustomCertificateAuthorityServiceInterceptor()) + client = CertificateAuthorityServiceClient(transport=transport) + + + """ + + def pre_activate_certificate_authority( + self, + request: service.ActivateCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ActivateCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for activate_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_activate_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for activate_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_create_certificate( + self, + request: service.CreateCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_create_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for create_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_create_certificate_authority( + self, + request: service.CreateCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_create_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_disable_certificate_authority( + self, + request: service.DisableCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DisableCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for disable_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_disable_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for disable_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_enable_certificate_authority( + self, + request: service.EnableCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.EnableCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for enable_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_enable_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for enable_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_fetch_certificate_authority_csr( + self, + request: service.FetchCertificateAuthorityCsrRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.FetchCertificateAuthorityCsrRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for fetch_certificate_authority_csr + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_fetch_certificate_authority_csr( + self, response: service.FetchCertificateAuthorityCsrResponse + ) -> service.FetchCertificateAuthorityCsrResponse: + """Post-rpc interceptor for fetch_certificate_authority_csr + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_certificate( + self, + request: service.GetCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for get_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_authority( + self, + request: service.GetCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_certificate_authority( + self, response: resources.CertificateAuthority + ) -> resources.CertificateAuthority: + """Post-rpc interceptor for get_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_certificate_revocation_list( + self, + request: service.GetCertificateRevocationListRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetCertificateRevocationListRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_certificate_revocation_list + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_certificate_revocation_list( + self, response: resources.CertificateRevocationList + ) -> resources.CertificateRevocationList: + """Post-rpc interceptor for get_certificate_revocation_list + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_get_reusable_config( + self, + request: service.GetReusableConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetReusableConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_reusable_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_get_reusable_config( + self, response: resources.ReusableConfig + ) -> resources.ReusableConfig: + """Post-rpc interceptor for get_reusable_config + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_authorities( + self, + request: service.ListCertificateAuthoritiesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListCertificateAuthoritiesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_certificate_authorities + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_certificate_authorities( + self, response: service.ListCertificateAuthoritiesResponse + ) -> service.ListCertificateAuthoritiesResponse: + """Post-rpc interceptor for list_certificate_authorities + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_certificate_revocation_lists( + self, + request: service.ListCertificateRevocationListsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + service.ListCertificateRevocationListsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_certificate_revocation_lists + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_certificate_revocation_lists( + self, response: service.ListCertificateRevocationListsResponse + ) -> service.ListCertificateRevocationListsResponse: + """Post-rpc interceptor for list_certificate_revocation_lists + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_certificates( + self, + request: service.ListCertificatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListCertificatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_certificates + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_certificates( + self, response: service.ListCertificatesResponse + ) -> service.ListCertificatesResponse: + """Post-rpc interceptor for list_certificates + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_list_reusable_configs( + self, + request: service.ListReusableConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ListReusableConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_reusable_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_list_reusable_configs( + self, response: service.ListReusableConfigsResponse + ) -> service.ListReusableConfigsResponse: + """Post-rpc interceptor for list_reusable_configs + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_restore_certificate_authority( + self, + request: service.RestoreCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.RestoreCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_restore_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_revoke_certificate( + self, + request: service.RevokeCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.RevokeCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for revoke_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_revoke_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for revoke_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_schedule_delete_certificate_authority( + self, + request: service.ScheduleDeleteCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + service.ScheduleDeleteCertificateAuthorityRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for schedule_delete_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_schedule_delete_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for schedule_delete_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_certificate( + self, + request: service.UpdateCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_certificate( + self, response: resources.Certificate + ) -> resources.Certificate: + """Post-rpc interceptor for update_certificate + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_certificate_authority( + self, + request: service.UpdateCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateCertificateAuthorityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_certificate_authority( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate_authority + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + def pre_update_certificate_revocation_list( + self, + request: service.UpdateCertificateRevocationListRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + service.UpdateCertificateRevocationListRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_certificate_revocation_list + + Override in a subclass to manipulate the request or metadata + before they are sent to the CertificateAuthorityService server. + """ + return request, metadata + + def post_update_certificate_revocation_list( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_certificate_revocation_list + + Override in a subclass to manipulate the response + after it is returned by the CertificateAuthorityService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CertificateAuthorityServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CertificateAuthorityServiceRestInterceptor + + +class CertificateAuthorityServiceRestTransport(CertificateAuthorityServiceTransport): + """REST backend transport for CertificateAuthorityService. + + [Certificate Authority + Service][google.cloud.security.privateca.v1beta1.CertificateAuthorityService] + manages private certificate authorities and issued certificates. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "privateca.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CertificateAuthorityServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` 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 are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CertificateAuthorityServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _ActivateCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ActivateCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ActivateCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the activate certificate + authority method over HTTP. + + Args: + request (~.service.ActivateCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.ActivateCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ActivateCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:activate", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_activate_certificate_authority( + request, metadata + ) + pb_request = service.ActivateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_activate_certificate_authority(resp) + return resp + + class _CreateCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("CreateCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the create certificate method over HTTP. + + Args: + request (~.service.CreateCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.CreateCertificate][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.CreateCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1beta1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates", + "body": "certificate", + }, + ] + request, metadata = self._interceptor.pre_create_certificate( + request, metadata + ) + pb_request = service.CreateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate(resp) + return resp + + class _CreateCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("CreateCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "certificateAuthorityId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.CreateCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create certificate + authority method over HTTP. + + Args: + request (~.service.CreateCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.CreateCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.CreateCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities", + "body": "certificate_authority", + }, + ] + request, metadata = self._interceptor.pre_create_certificate_authority( + request, metadata + ) + pb_request = service.CreateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_certificate_authority(resp) + return resp + + class _DisableCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("DisableCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.DisableCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the disable certificate + authority method over HTTP. + + Args: + request (~.service.DisableCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.DisableCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.DisableCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:disable", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_disable_certificate_authority( + request, metadata + ) + pb_request = service.DisableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_disable_certificate_authority(resp) + return resp + + class _EnableCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("EnableCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.EnableCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the enable certificate + authority method over HTTP. + + Args: + request (~.service.EnableCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.EnableCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.EnableCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:enable", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_enable_certificate_authority( + request, metadata + ) + pb_request = service.EnableCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_enable_certificate_authority(resp) + return resp + + class _FetchCertificateAuthorityCsr(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("FetchCertificateAuthorityCsr") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.FetchCertificateAuthorityCsrRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.FetchCertificateAuthorityCsrResponse: + r"""Call the fetch certificate + authority csr method over HTTP. + + Args: + request (~.service.FetchCertificateAuthorityCsrRequest): + The request object. Request message for + [CertificateAuthorityService.FetchCertificateAuthorityCsr][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.FetchCertificateAuthorityCsr]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.FetchCertificateAuthorityCsrResponse: + Response message for + [CertificateAuthorityService.FetchCertificateAuthorityCsr][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.FetchCertificateAuthorityCsr]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:fetch", + }, + ] + request, metadata = self._interceptor.pre_fetch_certificate_authority_csr( + request, metadata + ) + pb_request = service.FetchCertificateAuthorityCsrRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.FetchCertificateAuthorityCsrResponse() + pb_resp = service.FetchCertificateAuthorityCsrResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_certificate_authority_csr(resp) + return resp + + class _GetCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the get certificate method over HTTP. + + Args: + request (~.service.GetCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.GetCertificate][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.GetCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1beta1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate(request, metadata) + pb_request = service.GetCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate(resp) + return resp + + class _GetCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CertificateAuthority: + r"""Call the get certificate authority method over HTTP. + + Args: + request (~.service.GetCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.GetCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.GetCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CertificateAuthority: + A + [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority] + represents an individual Certificate Authority. A + [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority] + can be used to create + [Certificates][google.cloud.security.privateca.v1beta1.Certificate]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_authority( + request, metadata + ) + pb_request = service.GetCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CertificateAuthority() + pb_resp = resources.CertificateAuthority.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_authority(resp) + return resp + + class _GetCertificateRevocationList(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetCertificateRevocationList") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetCertificateRevocationListRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CertificateRevocationList: + r"""Call the get certificate + revocation list method over HTTP. + + Args: + request (~.service.GetCertificateRevocationListRequest): + The request object. Request message for + [CertificateAuthorityService.GetCertificateRevocationList][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.GetCertificateRevocationList]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CertificateRevocationList: + A + [CertificateRevocationList][google.cloud.security.privateca.v1beta1.CertificateRevocationList] + corresponds to a signed X.509 certificate Revocation + List (CRL). A CRL contains the serial numbers of + certificates that should no longer be trusted. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}", + }, + ] + request, metadata = self._interceptor.pre_get_certificate_revocation_list( + request, metadata + ) + pb_request = service.GetCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CertificateRevocationList() + pb_resp = resources.CertificateRevocationList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_certificate_revocation_list(resp) + return resp + + class _GetReusableConfig(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("GetReusableConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetReusableConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ReusableConfig: + r"""Call the get reusable config method over HTTP. + + Args: + request (~.service.GetReusableConfigRequest): + The request object. Request message for + [CertificateAuthorityService.GetReusableConfig][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.GetReusableConfig]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ReusableConfig: + A + [ReusableConfig][google.cloud.security.privateca.v1beta1.ReusableConfig] + refers to a managed + [ReusableConfigValues][google.cloud.security.privateca.v1beta1.ReusableConfigValues]. + Those, in turn, are used to describe certain fields of + an X.509 certificate, such as the key usage fields, + fields specific to CA certificates, certificate policy + extensions and custom extensions. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/reusableConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_reusable_config( + request, metadata + ) + pb_request = service.GetReusableConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.ReusableConfig() + pb_resp = resources.ReusableConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_reusable_config(resp) + return resp + + class _ListCertificateAuthorities(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCertificateAuthorities") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCertificateAuthoritiesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCertificateAuthoritiesResponse: + r"""Call the list certificate + authorities method over HTTP. + + Args: + request (~.service.ListCertificateAuthoritiesRequest): + The request object. Request message for + [CertificateAuthorityService.ListCertificateAuthorities][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListCertificateAuthorities]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCertificateAuthoritiesResponse: + Response message for + [CertificateAuthorityService.ListCertificateAuthorities][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListCertificateAuthorities]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_authorities( + request, metadata + ) + pb_request = service.ListCertificateAuthoritiesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCertificateAuthoritiesResponse() + pb_resp = service.ListCertificateAuthoritiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_authorities(resp) + return resp + + class _ListCertificateRevocationLists(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCertificateRevocationLists") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCertificateRevocationListsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCertificateRevocationListsResponse: + r"""Call the list certificate + revocation lists method over HTTP. + + Args: + request (~.service.ListCertificateRevocationListsRequest): + The request object. Request message for + [CertificateAuthorityService.ListCertificateRevocationLists][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListCertificateRevocationLists]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCertificateRevocationListsResponse: + Response message for + [CertificateAuthorityService.ListCertificateRevocationLists][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListCertificateRevocationLists]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificateRevocationLists", + }, + ] + request, metadata = self._interceptor.pre_list_certificate_revocation_lists( + request, metadata + ) + pb_request = service.ListCertificateRevocationListsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCertificateRevocationListsResponse() + pb_resp = service.ListCertificateRevocationListsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificate_revocation_lists(resp) + return resp + + class _ListCertificates(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListCertificates") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListCertificatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListCertificatesResponse: + r"""Call the list certificates method over HTTP. + + Args: + request (~.service.ListCertificatesRequest): + The request object. Request message for + [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListCertificates]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCertificatesResponse: + Response message for + [CertificateAuthorityService.ListCertificates][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListCertificates]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates", + }, + ] + request, metadata = self._interceptor.pre_list_certificates( + request, metadata + ) + pb_request = service.ListCertificatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCertificatesResponse() + pb_resp = service.ListCertificatesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_certificates(resp) + return resp + + class _ListReusableConfigs(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ListReusableConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ListReusableConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListReusableConfigsResponse: + r"""Call the list reusable configs method over HTTP. + + Args: + request (~.service.ListReusableConfigsRequest): + The request object. Request message for + [CertificateAuthorityService.ListReusableConfigs][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListReusableConfigs]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListReusableConfigsResponse: + Response message for + [CertificateAuthorityService.ListReusableConfigs][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ListReusableConfigs]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*/locations/*}/reusableConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_reusable_configs( + request, metadata + ) + pb_request = service.ListReusableConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListReusableConfigsResponse() + pb_resp = service.ListReusableConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_reusable_configs(resp) + return resp + + class _RestoreCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("RestoreCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.RestoreCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the restore certificate + authority method over HTTP. + + Args: + request (~.service.RestoreCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.RestoreCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.RestoreCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:restore", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_restore_certificate_authority( + request, metadata + ) + pb_request = service.RestoreCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restore_certificate_authority(resp) + return resp + + class _RevokeCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("RevokeCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.RevokeCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the revoke certificate method over HTTP. + + Args: + request (~.service.RevokeCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.RevokeCertificate][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.RevokeCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1beta1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}:revoke", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_revoke_certificate( + request, metadata + ) + pb_request = service.RevokeCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_revoke_certificate(resp) + return resp + + class _ScheduleDeleteCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("ScheduleDeleteCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.ScheduleDeleteCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the schedule delete + certificate authority method over HTTP. + + Args: + request (~.service.ScheduleDeleteCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.ScheduleDeleteCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.ScheduleDeleteCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:scheduleDelete", + "body": "*", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_schedule_delete_certificate_authority( + request, metadata + ) + pb_request = service.ScheduleDeleteCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_schedule_delete_certificate_authority(resp) + return resp + + class _UpdateCertificate(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Certificate: + r"""Call the update certificate method over HTTP. + + Args: + request (~.service.UpdateCertificateRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCertificate][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.UpdateCertificate]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Certificate: + A + [Certificate][google.cloud.security.privateca.v1beta1.Certificate] + corresponds to a signed X.509 certificate issued by a + [CertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthority]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{certificate.name=projects/*/locations/*/certificateAuthorities/*/certificates/*}", + "body": "certificate", + }, + ] + request, metadata = self._interceptor.pre_update_certificate( + request, metadata + ) + pb_request = service.UpdateCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.Certificate() + pb_resp = resources.Certificate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate(resp) + return resp + + class _UpdateCertificateAuthority(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCertificateAuthority") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate + authority method over HTTP. + + Args: + request (~.service.UpdateCertificateAuthorityRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCertificateAuthority][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.UpdateCertificateAuthority]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{certificate_authority.name=projects/*/locations/*/certificateAuthorities/*}", + "body": "certificate_authority", + }, + ] + request, metadata = self._interceptor.pre_update_certificate_authority( + request, metadata + ) + pb_request = service.UpdateCertificateAuthorityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate_authority(resp) + return resp + + class _UpdateCertificateRevocationList(CertificateAuthorityServiceRestStub): + def __hash__(self): + return hash("UpdateCertificateRevocationList") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.UpdateCertificateRevocationListRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update certificate + revocation list method over HTTP. + + Args: + request (~.service.UpdateCertificateRevocationListRequest): + The request object. Request message for + [CertificateAuthorityService.UpdateCertificateRevocationList][google.cloud.security.privateca.v1beta1.CertificateAuthorityService.UpdateCertificateRevocationList]. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta1/{certificate_revocation_list.name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}", + "body": "certificate_revocation_list", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_update_certificate_revocation_list( + request, metadata + ) + pb_request = service.UpdateCertificateRevocationListRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_certificate_revocation_list(resp) + return resp + + @property + def activate_certificate_authority( + self, + ) -> Callable[ + [service.ActivateCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ActivateCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate( + self, + ) -> Callable[[service.CreateCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_certificate_authority( + self, + ) -> Callable[ + [service.CreateCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def disable_certificate_authority( + self, + ) -> Callable[ + [service.DisableCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DisableCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def enable_certificate_authority( + self, + ) -> Callable[ + [service.EnableCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._EnableCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_certificate_authority_csr( + self, + ) -> Callable[ + [service.FetchCertificateAuthorityCsrRequest], + service.FetchCertificateAuthorityCsrResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FetchCertificateAuthorityCsr(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate( + self, + ) -> Callable[[service.GetCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_authority( + self, + ) -> Callable[ + [service.GetCertificateAuthorityRequest], resources.CertificateAuthority + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_certificate_revocation_list( + self, + ) -> Callable[ + [service.GetCertificateRevocationListRequest], + resources.CertificateRevocationList, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCertificateRevocationList(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_reusable_config( + self, + ) -> Callable[[service.GetReusableConfigRequest], resources.ReusableConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetReusableConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_authorities( + self, + ) -> Callable[ + [service.ListCertificateAuthoritiesRequest], + service.ListCertificateAuthoritiesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateAuthorities(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificate_revocation_lists( + self, + ) -> Callable[ + [service.ListCertificateRevocationListsRequest], + service.ListCertificateRevocationListsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificateRevocationLists(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_certificates( + self, + ) -> Callable[[service.ListCertificatesRequest], service.ListCertificatesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCertificates(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_reusable_configs( + self, + ) -> Callable[ + [service.ListReusableConfigsRequest], service.ListReusableConfigsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListReusableConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_certificate_authority( + self, + ) -> Callable[ + [service.RestoreCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def revoke_certificate( + self, + ) -> Callable[[service.RevokeCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RevokeCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def schedule_delete_certificate_authority( + self, + ) -> Callable[ + [service.ScheduleDeleteCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ScheduleDeleteCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate( + self, + ) -> Callable[[service.UpdateCertificateRequest], resources.Certificate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificate(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate_authority( + self, + ) -> Callable[ + [service.UpdateCertificateAuthorityRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificateAuthority(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_certificate_revocation_list( + self, + ) -> Callable[ + [service.UpdateCertificateRevocationListRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCertificateRevocationList(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CertificateAuthorityServiceRestTransport",) diff --git a/google/cloud/security/privateca_v1beta1/types/resources.py b/google/cloud/security/privateca_v1beta1/types/resources.py index eda44e9..fa36f4c 100644 --- a/google/cloud/security/privateca_v1beta1/types/resources.py +++ b/google/cloud/security/privateca_v1beta1/types/resources.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import duration_pb2 # type: ignore diff --git a/google/cloud/security/privateca_v1beta1/types/service.py b/google/cloud/security/privateca_v1beta1/types/service.py index 8136db2..c07d735 100644 --- a/google/cloud/security/privateca_v1beta1/types/service.py +++ b/google/cloud/security/privateca_v1beta1/types/service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import field_mask_pb2 # type: ignore diff --git a/setup.py b/setup.py index 62e0ab6..65cfb9c 100644 --- a/setup.py +++ b/setup.py @@ -42,6 +42,7 @@ "proto-plus >= 1.22.0, <2.0.0dev", "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, < 1.0.0dev", ] url = "https://github.com/googleapis/python-security-private-ca" diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.10.txt +++ b/testing/constraints-3.10.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.11.txt +++ b/testing/constraints-3.11.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/testing/constraints-3.12.txt b/testing/constraints-3.12.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.12.txt +++ b/testing/constraints-3.12.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 6c44adf..2beecf9 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -7,3 +7,4 @@ google-api-core==1.34.0 proto-plus==1.22.0 protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.8.txt +++ b/testing/constraints-3.8.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.9.txt +++ b/testing/constraints-3.9.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py b/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py index 2a111bb..c329840 100644 --- a/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py +++ b/tests/unit/gapic/privateca_v1/test_certificate_authority_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import ( @@ -39,11 +41,16 @@ import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.type import expr_pb2 # type: ignore import grpc @@ -51,6 +58,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.security.privateca_v1.services.certificate_authority_service import ( CertificateAuthorityServiceAsyncClient, @@ -113,6 +122,7 @@ def test__get_default_mtls_endpoint(): [ (CertificateAuthorityServiceClient, "grpc"), (CertificateAuthorityServiceAsyncClient, "grpc_asyncio"), + (CertificateAuthorityServiceClient, "rest"), ], ) def test_certificate_authority_service_client_from_service_account_info( @@ -128,7 +138,11 @@ def test_certificate_authority_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("privateca.googleapis.com:443") + assert client.transport._host == ( + "privateca.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com" + ) @pytest.mark.parametrize( @@ -136,6 +150,7 @@ def test_certificate_authority_service_client_from_service_account_info( [ (transports.CertificateAuthorityServiceGrpcTransport, "grpc"), (transports.CertificateAuthorityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CertificateAuthorityServiceRestTransport, "rest"), ], ) def test_certificate_authority_service_client_service_account_always_use_jwt( @@ -161,6 +176,7 @@ def test_certificate_authority_service_client_service_account_always_use_jwt( [ (CertificateAuthorityServiceClient, "grpc"), (CertificateAuthorityServiceAsyncClient, "grpc_asyncio"), + (CertificateAuthorityServiceClient, "rest"), ], ) def test_certificate_authority_service_client_from_service_account_file( @@ -183,13 +199,18 @@ def test_certificate_authority_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("privateca.googleapis.com:443") + assert client.transport._host == ( + "privateca.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com" + ) def test_certificate_authority_service_client_get_transport_class(): transport = CertificateAuthorityServiceClient.get_transport_class() available_transports = [ transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceRestTransport, ] assert transport in available_transports @@ -210,6 +231,11 @@ def test_certificate_authority_service_client_get_transport_class(): transports.CertificateAuthorityServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -369,6 +395,18 @@ def test_certificate_authority_service_client_client_options( "grpc_asyncio", "false", ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + "true", + ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -575,6 +613,11 @@ def test_certificate_authority_service_client_get_mtls_endpoint_and_cert_source( transports.CertificateAuthorityServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + ), ], ) def test_certificate_authority_service_client_client_options_scopes( @@ -615,6 +658,12 @@ def test_certificate_authority_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + None, + ), ], ) def test_certificate_authority_service_client_client_options_credentials_file( @@ -8949,861 +8998,13449 @@ async def test_update_certificate_template_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateRequest, + dict, + ], +) +def test_create_certificate_rest(request_type): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request_init["certificate"] = { + "name": "name_value", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "issuer_certificate_authority": "issuer_certificate_authority_value", + "lifetime": {"seconds": 751, "nanos": 543}, + "certificate_template": "certificate_template_value", + "subject_mode": 1, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_create_certificate_rest_required_fields( + request_type=service.CreateCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "certificate_id", + "issuing_certificate_authority_id", + "request_id", + "validate_only", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide an api_key and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options=options, - transport=transport, + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "certificateId", + "issuingCertificateAuthorityId", + "requestId", + "validateOnly", + ) ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + & set( + ( + "parent", + "certificate", + ) ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_create_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_create_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateRequest.pb( + service.CreateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() ) + request = service.CreateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + client.create_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_rest_bad_request( + transport: str = "rest", request_type=service.CreateCertificateRequest +): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = CertificateAuthorityServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request_init["certificate"] = { + "name": "name_value", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "issuer_certificate_authority": "issuer_certificate_authority_value", + "lifetime": {"seconds": 751, "nanos": 543}, + "certificate_template": "certificate_template_value", + "subject_mode": 1, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate(request) + + +def test_create_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + certificate=resources.Certificate(name="name_value"), + certificate_id="certificate_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/caPools/*}/certificates" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_certificate( + service.CreateCertificateRequest(), + parent="parent_value", + certificate=resources.Certificate(name="name_value"), + certificate_id="certificate_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_create_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + service.GetCertificateRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = CertificateAuthorityServiceClient.get_transport_class(transport_name)( +def test_get_certificate_rest(request_type): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_get_certificate_rest_required_fields( + request_type=service.GetCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.CertificateAuthorityServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_certificate_authority_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CertificateAuthorityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_get_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_get_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateRequest.pb(service.GetCertificateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() ) + request = service.GetCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() -def test_certificate_authority_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CertificateAuthorityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.get_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_certificate", - "get_certificate", - "list_certificates", - "revoke_certificate", - "update_certificate", - "activate_certificate_authority", - "create_certificate_authority", - "disable_certificate_authority", - "enable_certificate_authority", - "fetch_certificate_authority_csr", - "get_certificate_authority", - "list_certificate_authorities", - "undelete_certificate_authority", - "delete_certificate_authority", - "update_certificate_authority", - "create_ca_pool", - "update_ca_pool", - "get_ca_pool", - "list_ca_pools", - "delete_ca_pool", - "fetch_ca_certs", - "get_certificate_revocation_list", - "list_certificate_revocation_lists", - "update_certificate_revocation_list", - "create_certificate_template", - "delete_certificate_template", - "get_certificate_template", - "list_certificate_templates", - "update_certificate_template", + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_rest_bad_request( + transport: str = "rest", request_type=service.GetCertificateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + request = request_type(**request_init) - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate(request) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +def test_get_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -def test_certificate_authority_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CertificateAuthorityServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } -def test_certificate_authority_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CertificateAuthorityServiceTransport() - adc.assert_called_once() + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_certificate_authority_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - CertificateAuthorityServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, + client.get_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificates/*}" + % client.transport._host, + args[1], ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", +def test_get_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_certificate( + service.GetCertificateRequest(), + name="name_value", ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) +def test_get_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_class,grpc_helpers", + "request_type", [ - (transports.CertificateAuthorityServiceGrpcTransport, grpc_helpers), - ( - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - grpc_helpers_async, - ), + service.ListCertificatesRequest, + dict, ], ) -def test_certificate_authority_service_transport_create_channel( - transport_class, grpc_helpers -): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) +def test_list_certificates_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - create_channel.assert_called_with( - "privateca.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="privateca.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_grpc_transport_client_cert_source_for_mtls( - transport_class, + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificates_rest_required_fields( + request_type=service.ListCertificatesRequest, ): - cred = ga_credentials.AnonymousCredentials() + transport_class = transports.CertificateAuthorityServiceRestTransport - # 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, + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificates._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificates._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", ) + ) + jsonified_request.update(unset_fields) - # 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 + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificatesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificates(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificates_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificates._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", ) + ) + & set(("parent",)) + ) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_certificate_authority_service_host_no_port(transport_name): +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificates_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_list_certificates" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_list_certificates" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificatesRequest.pb( + service.ListCertificatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCertificatesResponse.to_json( + service.ListCertificatesResponse() + ) + + request = service.ListCertificatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificatesResponse() + + client.list_certificates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificates_rest_bad_request( + transport: str = "rest", request_type=service.ListCertificatesRequest +): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="privateca.googleapis.com" - ), - transport=transport_name, + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificates(request) + + +def test_list_certificates_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificatesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificates(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/caPools/*}/certificates" + % client.transport._host, + args[1], + ) + + +def test_list_certificates_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificates( + service.ListCertificatesRequest(), + parent="parent_value", + ) + + +def test_list_certificates_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert client.transport._host == ("privateca.googleapis.com:443") + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + resources.Certificate(), + resources.Certificate(), + ], + next_page_token="abc", + ), + service.ListCertificatesResponse( + certificates=[], + next_page_token="def", + ), + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + ], + next_page_token="ghi", + ), + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + resources.Certificate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListCertificatesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3" + } + + pager = client.list_certificates(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Certificate) for i in results) + + pages = list(client.list_certificates(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", - "grpc_asyncio", + service.RevokeCertificateRequest, + dict, ], ) -def test_certificate_authority_service_host_with_port(transport_name): +def test_revoke_certificate_rest(request_type): client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="privateca.googleapis.com:8000" - ), - transport=transport_name, + transport="rest", ) - assert client.transport._host == ("privateca.googleapis.com:8000") + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + request = request_type(**request_init) -def test_certificate_authority_service_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) - # Check that channel is used if provided. - transport = transports.CertificateAuthorityServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.revoke_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_revoke_certificate_rest_required_fields( + request_type=service.RevokeCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # verify fields with default values are dropped -def test_certificate_authority_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).revoke_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Check that channel is used if provided. - transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).revoke_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.revoke_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_revoke_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.revoke_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "reason", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_revoke_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_revoke_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_revoke_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RevokeCertificateRequest.pb( + service.RevokeCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() + ) + + request = service.RevokeCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.revoke_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_revoke_certificate_rest_bad_request( + transport: str = "rest", request_type=service.RevokeCertificateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.revoke_certificate(request) + + +def test_revoke_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.revoke_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificates/*}:revoke" + % client.transport._host, + args[1], + ) + + +def test_revoke_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.revoke_certificate( + service.RevokeCertificateRequest(), + name="name_value", + ) + + +def test_revoke_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - 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", + "request_type", [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + service.UpdateCertificateRequest, + dict, ], ) -def test_certificate_authority_service_transport_channel_mtls_with_client_cert_source( - transport_class, -): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred +def test_update_certificate_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "issuer_certificate_authority": "issuer_certificate_authority_value", + "lifetime": {"seconds": 751, "nanos": 543}, + "certificate_template": "certificate_template_value", + "subject_mode": 1, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + issuer_certificate_authority="issuer_certificate_authority_value", + certificate_template="certificate_template_value", + subject_mode=resources.SubjectRequestMode.DEFAULT, + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.issuer_certificate_authority == "issuer_certificate_authority_value" + assert response.certificate_template == "certificate_template_value" + assert response.subject_mode == resources.SubjectRequestMode.DEFAULT + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_update_certificate_rest_required_fields( + request_type=service.UpdateCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificate", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_update_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_update_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateRequest.pb( + service.UpdateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() + ) + + request = service.UpdateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.update_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCertificateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "issuer_certificate_authority": "issuer_certificate_authority_value", + "lifetime": {"seconds": 751, "nanos": 543}, + "certificate_template": "certificate_template_value", + "subject_mode": 1, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate(request) + + +def test_update_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificates/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate=resources.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{certificate.name=projects/*/locations/*/caPools/*/certificates/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate( + service.UpdateCertificateRequest(), + certificate=resources.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ActivateCertificateAuthorityRequest, + dict, + ], +) +def test_activate_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.activate_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_activate_certificate_authority_rest_required_fields( + request_type=service.ActivateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["pem_ca_certificate"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).activate_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["pemCaCertificate"] = "pem_ca_certificate_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).activate_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "pemCaCertificate" in jsonified_request + assert jsonified_request["pemCaCertificate"] == "pem_ca_certificate_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.activate_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_activate_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.activate_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "pemCaCertificate", + "subordinateConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_activate_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_activate_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_activate_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ActivateCertificateAuthorityRequest.pb( + service.ActivateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.ActivateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.activate_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_activate_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.ActivateCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.activate_certificate_authority(request) + + +def test_activate_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.activate_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:activate" + % client.transport._host, + args[1], + ) + + +def test_activate_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.activate_certificate_authority( + service.ActivateCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_activate_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateAuthorityRequest, + dict, + ], +) +def test_create_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request_init["certificate_authority"] = { + "name": "name_value", + "type_": 1, + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "tier": 1, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_certificate_authority_rest_required_fields( + request_type=service.CreateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["certificate_authority_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "certificateAuthorityId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "certificateAuthorityId" in jsonified_request + assert ( + jsonified_request["certificateAuthorityId"] + == request_init["certificate_authority_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["certificateAuthorityId"] = "certificate_authority_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_authority._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "certificate_authority_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "certificateAuthorityId" in jsonified_request + assert ( + jsonified_request["certificateAuthorityId"] == "certificate_authority_id_value" + ) + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate_authority(request) + + expected_params = [ + ( + "certificateAuthorityId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "certificateAuthorityId", + "requestId", + ) + ) + & set( + ( + "parent", + "certificateAuthorityId", + "certificateAuthority", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_create_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_create_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateAuthorityRequest.pb( + service.CreateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.CreateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.CreateCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request_init["certificate_authority"] = { + "name": "name_value", + "type_": 1, + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "tier": 1, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate_authority(request) + + +def test_create_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + certificate_authority=resources.CertificateAuthority(name="name_value"), + certificate_authority_id="certificate_authority_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_certificate_authority( + service.CreateCertificateAuthorityRequest(), + parent="parent_value", + certificate_authority=resources.CertificateAuthority(name="name_value"), + certificate_authority_id="certificate_authority_id_value", + ) + + +def test_create_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DisableCertificateAuthorityRequest, + dict, + ], +) +def test_disable_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.disable_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_disable_certificate_authority_rest_required_fields( + request_type=service.DisableCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.disable_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_disable_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.disable_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_disable_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_disable_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DisableCertificateAuthorityRequest.pb( + service.DisableCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.DisableCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.disable_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_disable_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.DisableCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.disable_certificate_authority(request) + + +def test_disable_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.disable_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:disable" + % client.transport._host, + args[1], + ) + + +def test_disable_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.disable_certificate_authority( + service.DisableCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_disable_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.EnableCertificateAuthorityRequest, + dict, + ], +) +def test_enable_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.enable_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_enable_certificate_authority_rest_required_fields( + request_type=service.EnableCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.enable_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_enable_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.enable_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enable_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_enable_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_enable_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.EnableCertificateAuthorityRequest.pb( + service.EnableCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.EnableCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.enable_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_enable_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.EnableCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.enable_certificate_authority(request) + + +def test_enable_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.enable_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:enable" + % client.transport._host, + args[1], + ) + + +def test_enable_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.enable_certificate_authority( + service.EnableCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_enable_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.FetchCertificateAuthorityCsrRequest, + dict, + ], +) +def test_fetch_certificate_authority_csr_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.FetchCertificateAuthorityCsrResponse( + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.fetch_certificate_authority_csr(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.FetchCertificateAuthorityCsrResponse) + assert response.pem_csr == "pem_csr_value" + + +def test_fetch_certificate_authority_csr_rest_required_fields( + request_type=service.FetchCertificateAuthorityCsrRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_certificate_authority_csr._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_certificate_authority_csr._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.FetchCertificateAuthorityCsrResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.FetchCertificateAuthorityCsrResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.fetch_certificate_authority_csr(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_fetch_certificate_authority_csr_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.fetch_certificate_authority_csr._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_fetch_certificate_authority_csr", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_fetch_certificate_authority_csr", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FetchCertificateAuthorityCsrRequest.pb( + service.FetchCertificateAuthorityCsrRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + service.FetchCertificateAuthorityCsrResponse.to_json( + service.FetchCertificateAuthorityCsrResponse() + ) + ) + + request = service.FetchCertificateAuthorityCsrRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.FetchCertificateAuthorityCsrResponse() + + client.fetch_certificate_authority_csr( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_certificate_authority_csr_rest_bad_request( + transport: str = "rest", request_type=service.FetchCertificateAuthorityCsrRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_certificate_authority_csr(request) + + +def test_fetch_certificate_authority_csr_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.FetchCertificateAuthorityCsrResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.fetch_certificate_authority_csr(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:fetch" + % client.transport._host, + args[1], + ) + + +def test_fetch_certificate_authority_csr_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_certificate_authority_csr( + service.FetchCertificateAuthorityCsrRequest(), + name="name_value", + ) + + +def test_fetch_certificate_authority_csr_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateAuthorityRequest, + dict, + ], +) +def test_get_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateAuthority( + name="name_value", + type_=resources.CertificateAuthority.Type.SELF_SIGNED, + tier=resources.CaPool.Tier.ENTERPRISE, + state=resources.CertificateAuthority.State.ENABLED, + pem_ca_certificates=["pem_ca_certificates_value"], + gcs_bucket="gcs_bucket_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateAuthority) + assert response.name == "name_value" + assert response.type_ == resources.CertificateAuthority.Type.SELF_SIGNED + assert response.tier == resources.CaPool.Tier.ENTERPRISE + assert response.state == resources.CertificateAuthority.State.ENABLED + assert response.pem_ca_certificates == ["pem_ca_certificates_value"] + assert response.gcs_bucket == "gcs_bucket_value" + + +def test_get_certificate_authority_rest_required_fields( + request_type=service.GetCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CertificateAuthority() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateAuthorityRequest.pb( + service.GetCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.CertificateAuthority.to_json( + resources.CertificateAuthority() + ) + + request = service.GetCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateAuthority() + + client.get_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.GetCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_authority(request) + + +def test_get_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateAuthority() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_certificate_authority( + service.GetCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_get_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateAuthoritiesRequest, + dict, + ], +) +def test_list_certificate_authorities_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_authorities(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateAuthoritiesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_authorities_rest_required_fields( + request_type=service.ListCertificateAuthoritiesRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_authorities._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_authorities._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCertificateAuthoritiesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_authorities(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_authorities_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificate_authorities._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_authorities_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_authorities", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_authorities", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateAuthoritiesRequest.pb( + service.ListCertificateAuthoritiesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCertificateAuthoritiesResponse.to_json( + service.ListCertificateAuthoritiesResponse() + ) + + request = service.ListCertificateAuthoritiesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateAuthoritiesResponse() + + client.list_certificate_authorities( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_authorities_rest_bad_request( + transport: str = "rest", request_type=service.ListCertificateAuthoritiesRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_authorities(request) + + +def test_list_certificate_authorities_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_authorities(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/caPools/*}/certificateAuthorities" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_authorities_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificate_authorities( + service.ListCertificateAuthoritiesRequest(), + parent="parent_value", + ) + + +def test_list_certificate_authorities_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + resources.CertificateAuthority(), + resources.CertificateAuthority(), + ], + next_page_token="abc", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[], + next_page_token="def", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + ], + next_page_token="ghi", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + resources.CertificateAuthority(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCertificateAuthoritiesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3" + } + + pager = client.list_certificate_authorities(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CertificateAuthority) for i in results) + + pages = list(client.list_certificate_authorities(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.UndeleteCertificateAuthorityRequest, + dict, + ], +) +def test_undelete_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.undelete_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_undelete_certificate_authority_rest_required_fields( + request_type=service.UndeleteCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.undelete_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_undelete_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.undelete_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_undelete_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_undelete_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UndeleteCertificateAuthorityRequest.pb( + service.UndeleteCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UndeleteCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.undelete_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_undelete_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.UndeleteCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.undelete_certificate_authority(request) + + +def test_undelete_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.undelete_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}:undelete" + % client.transport._host, + args[1], + ) + + +def test_undelete_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.undelete_certificate_authority( + service.UndeleteCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_undelete_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCertificateAuthorityRequest, + dict, + ], +) +def test_delete_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_certificate_authority_rest_required_fields( + request_type=service.DeleteCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_authority._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "ignore_active_certificates", + "request_id", + "skip_grace_period", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "ignoreActiveCertificates", + "requestId", + "skipGracePeriod", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_delete_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_delete_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteCertificateAuthorityRequest.pb( + service.DeleteCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.DeleteCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.DeleteCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_certificate_authority(request) + + +def test_delete_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_certificate_authority( + service.DeleteCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_delete_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateAuthorityRequest, + dict, + ], +) +def test_update_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + } + request_init["certificate_authority"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4", + "type_": 1, + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "tier": 1, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_authority_rest_required_fields( + request_type=service.UpdateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_authority._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificateAuthority", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateAuthorityRequest.pb( + service.UpdateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + } + request_init["certificate_authority"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4", + "type_": 1, + "config": { + "subject_config": { + "subject": { + "common_name": "common_name_value", + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "x509_config": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": {}, + }, + "public_key": {"key": b"key_blob", "format_": 1}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "tier": 1, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "x509_description": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_urls": ["crl_access_urls_value1", "crl_access_urls_value2"], + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "expire_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate_authority(request) + + +def test_update_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_authority=resources.CertificateAuthority(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{certificate_authority.name=projects/*/locations/*/caPools/*/certificateAuthorities/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate_authority( + service.UpdateCertificateAuthorityRequest(), + certificate_authority=resources.CertificateAuthority(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCaPoolRequest, + dict, + ], +) +def test_create_ca_pool_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["ca_pool"] = { + "name": "name_value", + "tier": 1, + "issuance_policy": { + "allowed_key_types": [ + { + "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, + "elliptic_curve": {"signature_algorithm": 1}, + } + ], + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + "baseline_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + }, + "publishing_options": {"publish_ca_cert": True, "publish_crl": True}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_ca_pool(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_ca_pool_rest_required_fields(request_type=service.CreateCaPoolRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["ca_pool_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "caPoolId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_ca_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "caPoolId" in jsonified_request + assert jsonified_request["caPoolId"] == request_init["ca_pool_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["caPoolId"] = "ca_pool_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_ca_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "ca_pool_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "caPoolId" in jsonified_request + assert jsonified_request["caPoolId"] == "ca_pool_id_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_ca_pool(request) + + expected_params = [ + ( + "caPoolId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_ca_pool_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_ca_pool._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "caPoolId", + "requestId", + ) + ) + & set( + ( + "parent", + "caPoolId", + "caPool", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_create_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_create_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCaPoolRequest.pb(service.CreateCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.CreateCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_ca_pool_rest_bad_request( + transport: str = "rest", request_type=service.CreateCaPoolRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["ca_pool"] = { + "name": "name_value", + "tier": 1, + "issuance_policy": { + "allowed_key_types": [ + { + "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, + "elliptic_curve": {"signature_algorithm": 1}, + } + ], + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + "baseline_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + }, + "publishing_options": {"publish_ca_cert": True, "publish_crl": True}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_ca_pool(request) + + +def test_create_ca_pool_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ca_pool=resources.CaPool(name="name_value"), + ca_pool_id="ca_pool_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_ca_pool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/caPools" % client.transport._host, + args[1], + ) + + +def test_create_ca_pool_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_ca_pool( + service.CreateCaPoolRequest(), + parent="parent_value", + ca_pool=resources.CaPool(name="name_value"), + ca_pool_id="ca_pool_id_value", + ) + + +def test_create_ca_pool_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCaPoolRequest, + dict, + ], +) +def test_update_ca_pool_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "ca_pool": {"name": "projects/sample1/locations/sample2/caPools/sample3"} + } + request_init["ca_pool"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3", + "tier": 1, + "issuance_policy": { + "allowed_key_types": [ + { + "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, + "elliptic_curve": {"signature_algorithm": 1}, + } + ], + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + "baseline_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + }, + "publishing_options": {"publish_ca_cert": True, "publish_crl": True}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_ca_pool(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_ca_pool_rest_required_fields(request_type=service.UpdateCaPoolRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_ca_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_ca_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_ca_pool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_ca_pool_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_ca_pool._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "caPool", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_update_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_update_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCaPoolRequest.pb(service.UpdateCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_ca_pool_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCaPoolRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "ca_pool": {"name": "projects/sample1/locations/sample2/caPools/sample3"} + } + request_init["ca_pool"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3", + "tier": 1, + "issuance_policy": { + "allowed_key_types": [ + { + "rsa": {"min_modulus_size": 1734, "max_modulus_size": 1736}, + "elliptic_curve": {"signature_algorithm": 1}, + } + ], + "maximum_lifetime": {"seconds": 751, "nanos": 543}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + "baseline_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": [ + "permitted_uris_value1", + "permitted_uris_value2", + ], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + }, + "publishing_options": {"publish_ca_cert": True, "publish_crl": True}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_ca_pool(request) + + +def test_update_ca_pool_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "ca_pool": {"name": "projects/sample1/locations/sample2/caPools/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + ca_pool=resources.CaPool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_ca_pool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{ca_pool.name=projects/*/locations/*/caPools/*}" + % client.transport._host, + args[1], + ) + + +def test_update_ca_pool_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_ca_pool( + service.UpdateCaPoolRequest(), + ca_pool=resources.CaPool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_ca_pool_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCaPoolRequest, + dict, + ], +) +def test_get_ca_pool_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CaPool( + name="name_value", + tier=resources.CaPool.Tier.ENTERPRISE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CaPool.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_ca_pool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CaPool) + assert response.name == "name_value" + assert response.tier == resources.CaPool.Tier.ENTERPRISE + + +def test_get_ca_pool_rest_required_fields(request_type=service.GetCaPoolRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_ca_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_ca_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CaPool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CaPool.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_ca_pool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_ca_pool_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_ca_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_get_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_get_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCaPoolRequest.pb(service.GetCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.CaPool.to_json(resources.CaPool()) + + request = service.GetCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CaPool() + + client.get_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ca_pool_rest_bad_request( + transport: str = "rest", request_type=service.GetCaPoolRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_ca_pool(request) + + +def test_get_ca_pool_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CaPool() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/caPools/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CaPool.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_ca_pool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*}" % client.transport._host, + args[1], + ) + + +def test_get_ca_pool_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_ca_pool( + service.GetCaPoolRequest(), + name="name_value", + ) + + +def test_get_ca_pool_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCaPoolsRequest, + dict, + ], +) +def test_list_ca_pools_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCaPoolsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCaPoolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_ca_pools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCaPoolsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_ca_pools_rest_required_fields(request_type=service.ListCaPoolsRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_ca_pools._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_ca_pools._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCaPoolsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCaPoolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_ca_pools(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_ca_pools_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_ca_pools._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_ca_pools_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_list_ca_pools" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_list_ca_pools" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCaPoolsRequest.pb(service.ListCaPoolsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCaPoolsResponse.to_json( + service.ListCaPoolsResponse() + ) + + request = service.ListCaPoolsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCaPoolsResponse() + + client.list_ca_pools( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_ca_pools_rest_bad_request( + transport: str = "rest", request_type=service.ListCaPoolsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_ca_pools(request) + + +def test_list_ca_pools_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCaPoolsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCaPoolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_ca_pools(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/caPools" % client.transport._host, + args[1], + ) + + +def test_list_ca_pools_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_ca_pools( + service.ListCaPoolsRequest(), + parent="parent_value", + ) + + +def test_list_ca_pools_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCaPoolsResponse( + ca_pools=[ + resources.CaPool(), + resources.CaPool(), + resources.CaPool(), + ], + next_page_token="abc", + ), + service.ListCaPoolsResponse( + ca_pools=[], + next_page_token="def", + ), + service.ListCaPoolsResponse( + ca_pools=[ + resources.CaPool(), + ], + next_page_token="ghi", + ), + service.ListCaPoolsResponse( + ca_pools=[ + resources.CaPool(), + resources.CaPool(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListCaPoolsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_ca_pools(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CaPool) for i in results) + + pages = list(client.list_ca_pools(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCaPoolRequest, + dict, + ], +) +def test_delete_ca_pool_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_ca_pool(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_ca_pool_rest_required_fields(request_type=service.DeleteCaPoolRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_ca_pool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_ca_pool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_ca_pool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_ca_pool_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_ca_pool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_ca_pool_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_delete_ca_pool" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_delete_ca_pool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteCaPoolRequest.pb(service.DeleteCaPoolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.DeleteCaPoolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_ca_pool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_ca_pool_rest_bad_request( + transport: str = "rest", request_type=service.DeleteCaPoolRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_ca_pool(request) + + +def test_delete_ca_pool_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/caPools/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_ca_pool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*}" % client.transport._host, + args[1], + ) + + +def test_delete_ca_pool_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_ca_pool( + service.DeleteCaPoolRequest(), + name="name_value", + ) + + +def test_delete_ca_pool_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.FetchCaCertsRequest, + dict, + ], +) +def test_fetch_ca_certs_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"ca_pool": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.FetchCaCertsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.FetchCaCertsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.fetch_ca_certs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.FetchCaCertsResponse) + + +def test_fetch_ca_certs_rest_required_fields(request_type=service.FetchCaCertsRequest): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["ca_pool"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_ca_certs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["caPool"] = "ca_pool_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_ca_certs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "caPool" in jsonified_request + assert jsonified_request["caPool"] == "ca_pool_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.FetchCaCertsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.FetchCaCertsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.fetch_ca_certs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_fetch_ca_certs_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.fetch_ca_certs._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("caPool",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_ca_certs_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_fetch_ca_certs" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_fetch_ca_certs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FetchCaCertsRequest.pb(service.FetchCaCertsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.FetchCaCertsResponse.to_json( + service.FetchCaCertsResponse() + ) + + request = service.FetchCaCertsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.FetchCaCertsResponse() + + client.fetch_ca_certs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_ca_certs_rest_bad_request( + transport: str = "rest", request_type=service.FetchCaCertsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"ca_pool": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_ca_certs(request) + + +def test_fetch_ca_certs_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.FetchCaCertsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "ca_pool": "projects/sample1/locations/sample2/caPools/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + ca_pool="ca_pool_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.FetchCaCertsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.fetch_ca_certs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{ca_pool=projects/*/locations/*/caPools/*}:fetchCaCerts" + % client.transport._host, + args[1], + ) + + +def test_fetch_ca_certs_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_ca_certs( + service.FetchCaCertsRequest(), + ca_pool="ca_pool_value", + ) + + +def test_fetch_ca_certs_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateRevocationListRequest, + dict, + ], +) +def test_get_certificate_revocation_list_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateRevocationList( + name="name_value", + sequence_number=1601, + pem_crl="pem_crl_value", + access_url="access_url_value", + state=resources.CertificateRevocationList.State.ACTIVE, + revision_id="revision_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_revocation_list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateRevocationList) + assert response.name == "name_value" + assert response.sequence_number == 1601 + assert response.pem_crl == "pem_crl_value" + assert response.access_url == "access_url_value" + assert response.state == resources.CertificateRevocationList.State.ACTIVE + assert response.revision_id == "revision_id_value" + + +def test_get_certificate_revocation_list_rest_required_fields( + request_type=service.GetCertificateRevocationListRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_revocation_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_revocation_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CertificateRevocationList() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_revocation_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_revocation_list_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_revocation_list._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_revocation_list", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_revocation_list", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateRevocationListRequest.pb( + service.GetCertificateRevocationListRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.CertificateRevocationList.to_json( + resources.CertificateRevocationList() + ) + + request = service.GetCertificateRevocationListRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateRevocationList() + + client.get_certificate_revocation_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_revocation_list_rest_bad_request( + transport: str = "rest", request_type=service.GetCertificateRevocationListRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_revocation_list(request) + + +def test_get_certificate_revocation_list_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateRevocationList() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_revocation_list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_revocation_list_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_certificate_revocation_list( + service.GetCertificateRevocationListRequest(), + name="name_value", + ) + + +def test_get_certificate_revocation_list_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateRevocationListsRequest, + dict, + ], +) +def test_list_certificate_revocation_lists_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateRevocationListsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateRevocationListsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_revocation_lists(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateRevocationListsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_revocation_lists_rest_required_fields( + request_type=service.ListCertificateRevocationListsRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_revocation_lists._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_revocation_lists._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateRevocationListsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCertificateRevocationListsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_revocation_lists(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_revocation_lists_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_certificate_revocation_lists._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_revocation_lists", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_revocation_lists", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateRevocationListsRequest.pb( + service.ListCertificateRevocationListsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + service.ListCertificateRevocationListsResponse.to_json( + service.ListCertificateRevocationListsResponse() + ) + ) + + request = service.ListCertificateRevocationListsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateRevocationListsResponse() + + client.list_certificate_revocation_lists( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_revocation_lists_rest_bad_request( + transport: str = "rest", request_type=service.ListCertificateRevocationListsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_revocation_lists(request) + + +def test_list_certificate_revocation_lists_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateRevocationListsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateRevocationListsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_revocation_lists(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/caPools/*/certificateAuthorities/*}/certificateRevocationLists" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_revocation_lists_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificate_revocation_lists( + service.ListCertificateRevocationListsRequest(), + parent="parent_value", + ) + + +def test_list_certificate_revocation_lists_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + ], + next_page_token="abc", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[], + next_page_token="def", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + ], + next_page_token="ghi", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCertificateRevocationListsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4" + } + + pager = client.list_certificate_revocation_lists(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CertificateRevocationList) for i in results) + + pages = list( + client.list_certificate_revocation_lists(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateRevocationListRequest, + dict, + ], +) +def test_update_certificate_revocation_list_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + } + request_init["certificate_revocation_list"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5", + "sequence_number": 1601, + "revoked_certificates": [ + { + "certificate": "certificate_value", + "hex_serial_number": "hex_serial_number_value", + "revocation_reason": 1, + } + ], + "pem_crl": "pem_crl_value", + "access_url": "access_url_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "revision_id": "revision_id_value", + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_revocation_list(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_revocation_list_rest_required_fields( + request_type=service.UpdateCertificateRevocationListRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_revocation_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_revocation_list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_revocation_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_revocation_list_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_certificate_revocation_list._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificateRevocationList", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_revocation_list_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_revocation_list", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_revocation_list", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateRevocationListRequest.pb( + service.UpdateCertificateRevocationListRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateCertificateRevocationListRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_revocation_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_revocation_list_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCertificateRevocationListRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + } + request_init["certificate_revocation_list"] = { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5", + "sequence_number": 1601, + "revoked_certificates": [ + { + "certificate": "certificate_value", + "hex_serial_number": "hex_serial_number_value", + "revocation_reason": 1, + } + ], + "pem_crl": "pem_crl_value", + "access_url": "access_url_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "revision_id": "revision_id_value", + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate_revocation_list(request) + + +def test_update_certificate_revocation_list_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/caPools/sample3/certificateAuthorities/sample4/certificateRevocationLists/sample5" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_revocation_list=resources.CertificateRevocationList( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_revocation_list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{certificate_revocation_list.name=projects/*/locations/*/caPools/*/certificateAuthorities/*/certificateRevocationLists/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_revocation_list_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate_revocation_list( + service.UpdateCertificateRevocationListRequest(), + certificate_revocation_list=resources.CertificateRevocationList( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_revocation_list_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateTemplateRequest, + dict, + ], +) +def test_create_certificate_template_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_template"] = { + "name": "name_value", + "predefined_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_template(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_certificate_template_rest_required_fields( + request_type=service.CreateCertificateTemplateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["certificate_template_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "certificateTemplateId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "certificateTemplateId" in jsonified_request + assert ( + jsonified_request["certificateTemplateId"] + == request_init["certificate_template_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["certificateTemplateId"] = "certificate_template_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_template._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "certificate_template_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "certificateTemplateId" in jsonified_request + assert jsonified_request["certificateTemplateId"] == "certificate_template_id_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate_template(request) + + expected_params = [ + ( + "certificateTemplateId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_template_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate_template._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "certificateTemplateId", + "requestId", + ) + ) + & set( + ( + "parent", + "certificateTemplateId", + "certificateTemplate", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_create_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_create_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateTemplateRequest.pb( + service.CreateCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.CreateCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_template_rest_bad_request( + transport: str = "rest", request_type=service.CreateCertificateTemplateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_template"] = { + "name": "name_value", + "predefined_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate_template(request) + + +def test_create_certificate_template_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + certificate_template=resources.CertificateTemplate(name="name_value"), + certificate_template_id="certificate_template_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate_template(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificateTemplates" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_template_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_certificate_template( + service.CreateCertificateTemplateRequest(), + parent="parent_value", + certificate_template=resources.CertificateTemplate(name="name_value"), + certificate_template_id="certificate_template_id_value", + ) + + +def test_create_certificate_template_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCertificateTemplateRequest, + dict, + ], +) +def test_delete_certificate_template_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_certificate_template(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_certificate_template_rest_required_fields( + request_type=service.DeleteCertificateTemplateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_certificate_template._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_certificate_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_certificate_template_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_certificate_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_delete_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_delete_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DeleteCertificateTemplateRequest.pb( + service.DeleteCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.DeleteCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_certificate_template_rest_bad_request( + transport: str = "rest", request_type=service.DeleteCertificateTemplateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_certificate_template(request) + + +def test_delete_certificate_template_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_certificate_template(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_certificate_template_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_certificate_template( + service.DeleteCertificateTemplateRequest(), + name="name_value", + ) + + +def test_delete_certificate_template_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateTemplateRequest, + dict, + ], +) +def test_get_certificate_template_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateTemplate( + name="name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_get_certificate_template_rest_required_fields( + request_type=service.GetCertificateTemplateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CertificateTemplate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CertificateTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_template_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateTemplateRequest.pb( + service.GetCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.CertificateTemplate.to_json( + resources.CertificateTemplate() + ) + + request = service.GetCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateTemplate() + + client.get_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_template_rest_bad_request( + transport: str = "rest", request_type=service.GetCertificateTemplateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_template(request) + + +def test_get_certificate_template_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_template(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/certificateTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_template_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_certificate_template( + service.GetCertificateTemplateRequest(), + name="name_value", + ) + + +def test_get_certificate_template_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateTemplatesRequest, + dict, + ], +) +def test_list_certificate_templates_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateTemplatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateTemplatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_templates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateTemplatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_templates_rest_required_fields( + request_type=service.ListCertificateTemplatesRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_templates._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_templates._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateTemplatesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCertificateTemplatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_templates(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_templates_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificate_templates._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_templates_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_templates", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_templates", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateTemplatesRequest.pb( + service.ListCertificateTemplatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCertificateTemplatesResponse.to_json( + service.ListCertificateTemplatesResponse() + ) + + request = service.ListCertificateTemplatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateTemplatesResponse() + + client.list_certificate_templates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_templates_rest_bad_request( + transport: str = "rest", request_type=service.ListCertificateTemplatesRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_templates(request) + + +def test_list_certificate_templates_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateTemplatesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateTemplatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_templates(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/certificateTemplates" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_templates_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificate_templates( + service.ListCertificateTemplatesRequest(), + parent="parent_value", + ) + + +def test_list_certificate_templates_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificateTemplatesResponse( + certificate_templates=[ + resources.CertificateTemplate(), + resources.CertificateTemplate(), + resources.CertificateTemplate(), + ], + next_page_token="abc", + ), + service.ListCertificateTemplatesResponse( + certificate_templates=[], + next_page_token="def", + ), + service.ListCertificateTemplatesResponse( + certificate_templates=[ + resources.CertificateTemplate(), + ], + next_page_token="ghi", + ), + service.ListCertificateTemplatesResponse( + certificate_templates=[ + resources.CertificateTemplate(), + resources.CertificateTemplate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCertificateTemplatesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_certificate_templates(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CertificateTemplate) for i in results) + + pages = list(client.list_certificate_templates(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateTemplateRequest, + dict, + ], +) +def test_update_certificate_template_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_template": { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + } + request_init["certificate_template"] = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3", + "predefined_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_template(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_template_rest_required_fields( + request_type=service.UpdateCertificateTemplateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_template._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_template_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate_template._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificateTemplate", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_template_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_template", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_template", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateTemplateRequest.pb( + service.UpdateCertificateTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateCertificateTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_template_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCertificateTemplateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_template": { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + } + request_init["certificate_template"] = { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3", + "predefined_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": [{"object_id_path": [1456, 1457]}], + }, + "ca_options": {"is_ca": True, "max_issuer_path_length": 2349}, + "policy_ids": {}, + "aia_ocsp_servers": ["aia_ocsp_servers_value1", "aia_ocsp_servers_value2"], + "name_constraints": { + "critical": True, + "permitted_dns_names": [ + "permitted_dns_names_value1", + "permitted_dns_names_value2", + ], + "excluded_dns_names": [ + "excluded_dns_names_value1", + "excluded_dns_names_value2", + ], + "permitted_ip_ranges": [ + "permitted_ip_ranges_value1", + "permitted_ip_ranges_value2", + ], + "excluded_ip_ranges": [ + "excluded_ip_ranges_value1", + "excluded_ip_ranges_value2", + ], + "permitted_email_addresses": [ + "permitted_email_addresses_value1", + "permitted_email_addresses_value2", + ], + "excluded_email_addresses": [ + "excluded_email_addresses_value1", + "excluded_email_addresses_value2", + ], + "permitted_uris": ["permitted_uris_value1", "permitted_uris_value2"], + "excluded_uris": ["excluded_uris_value1", "excluded_uris_value2"], + }, + "additional_extensions": [ + {"object_id": {}, "critical": True, "value": b"value_blob"} + ], + }, + "identity_constraints": { + "cel_expression": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + "allow_subject_passthrough": True, + "allow_subject_alt_names_passthrough": True, + }, + "passthrough_extensions": { + "known_extensions": [1], + "additional_extensions": {}, + }, + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate_template(request) + + +def test_update_certificate_template_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_template": { + "name": "projects/sample1/locations/sample2/certificateTemplates/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_template=resources.CertificateTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_template(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{certificate_template.name=projects/*/locations/*/certificateTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_template_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate_template( + service.UpdateCertificateTemplateRequest(), + certificate_template=resources.CertificateTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_template_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + transports.CertificateAuthorityServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CertificateAuthorityServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CertificateAuthorityServiceGrpcTransport, + ) + + +def test_certificate_authority_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CertificateAuthorityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_certificate_authority_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CertificateAuthorityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_certificate", + "get_certificate", + "list_certificates", + "revoke_certificate", + "update_certificate", + "activate_certificate_authority", + "create_certificate_authority", + "disable_certificate_authority", + "enable_certificate_authority", + "fetch_certificate_authority_csr", + "get_certificate_authority", + "list_certificate_authorities", + "undelete_certificate_authority", + "delete_certificate_authority", + "update_certificate_authority", + "create_ca_pool", + "update_ca_pool", + "get_ca_pool", + "list_ca_pools", + "delete_ca_pool", + "fetch_ca_certs", + "get_certificate_revocation_list", + "list_certificate_revocation_lists", + "update_certificate_revocation_list", + "create_certificate_template", + "delete_certificate_template", + "get_certificate_template", + "list_certificate_templates", + "update_certificate_template", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_certificate_authority_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CertificateAuthorityServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_certificate_authority_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.security.privateca_v1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CertificateAuthorityServiceTransport() + adc.assert_called_once() + + +def test_certificate_authority_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CertificateAuthorityServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + ], +) +def test_certificate_authority_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + transports.CertificateAuthorityServiceRestTransport, + ], +) +def test_certificate_authority_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CertificateAuthorityServiceGrpcTransport, grpc_helpers), + ( + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_certificate_authority_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "privateca.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="privateca.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + ], +) +def test_certificate_authority_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_certificate_authority_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CertificateAuthorityServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_certificate_authority_service_rest_lro_client(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_certificate_authority_service_host_no_port(transport_name): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="privateca.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "privateca.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_certificate_authority_service_host_with_port(transport_name): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="privateca.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "privateca.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_certificate_authority_service_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CertificateAuthorityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CertificateAuthorityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_certificate._session + session2 = client2.transport.create_certificate._session + assert session1 != session2 + session1 = client1.transport.get_certificate._session + session2 = client2.transport.get_certificate._session + assert session1 != session2 + session1 = client1.transport.list_certificates._session + session2 = client2.transport.list_certificates._session + assert session1 != session2 + session1 = client1.transport.revoke_certificate._session + session2 = client2.transport.revoke_certificate._session + assert session1 != session2 + session1 = client1.transport.update_certificate._session + session2 = client2.transport.update_certificate._session + assert session1 != session2 + session1 = client1.transport.activate_certificate_authority._session + session2 = client2.transport.activate_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.create_certificate_authority._session + session2 = client2.transport.create_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.disable_certificate_authority._session + session2 = client2.transport.disable_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.enable_certificate_authority._session + session2 = client2.transport.enable_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.fetch_certificate_authority_csr._session + session2 = client2.transport.fetch_certificate_authority_csr._session + assert session1 != session2 + session1 = client1.transport.get_certificate_authority._session + session2 = client2.transport.get_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.list_certificate_authorities._session + session2 = client2.transport.list_certificate_authorities._session + assert session1 != session2 + session1 = client1.transport.undelete_certificate_authority._session + session2 = client2.transport.undelete_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.delete_certificate_authority._session + session2 = client2.transport.delete_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.update_certificate_authority._session + session2 = client2.transport.update_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.create_ca_pool._session + session2 = client2.transport.create_ca_pool._session + assert session1 != session2 + session1 = client1.transport.update_ca_pool._session + session2 = client2.transport.update_ca_pool._session + assert session1 != session2 + session1 = client1.transport.get_ca_pool._session + session2 = client2.transport.get_ca_pool._session + assert session1 != session2 + session1 = client1.transport.list_ca_pools._session + session2 = client2.transport.list_ca_pools._session + assert session1 != session2 + session1 = client1.transport.delete_ca_pool._session + session2 = client2.transport.delete_ca_pool._session + assert session1 != session2 + session1 = client1.transport.fetch_ca_certs._session + session2 = client2.transport.fetch_ca_certs._session + assert session1 != session2 + session1 = client1.transport.get_certificate_revocation_list._session + session2 = client2.transport.get_certificate_revocation_list._session + assert session1 != session2 + session1 = client1.transport.list_certificate_revocation_lists._session + session2 = client2.transport.list_certificate_revocation_lists._session + assert session1 != session2 + session1 = client1.transport.update_certificate_revocation_list._session + session2 = client2.transport.update_certificate_revocation_list._session + assert session1 != session2 + session1 = client1.transport.create_certificate_template._session + session2 = client2.transport.create_certificate_template._session + assert session1 != session2 + session1 = client1.transport.delete_certificate_template._session + session2 = client2.transport.delete_certificate_template._session + assert session1 != session2 + session1 = client1.transport.get_certificate_template._session + session2 = client2.transport.get_certificate_template._session + assert session1 != session2 + session1 = client1.transport.list_certificate_templates._session + session2 = client2.transport.list_certificate_templates._session + assert session1 != session2 + session1 = client1.transport.update_certificate_template._session + session2 = client2.transport.update_certificate_template._session + assert session1 != session2 + + +def test_certificate_authority_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CertificateAuthorityServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_certificate_authority_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=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", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + ], +) +def test_certificate_authority_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + 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", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + ], +) +def test_certificate_authority_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + 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 + + +def test_certificate_authority_service_grpc_lro_client(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_certificate_authority_service_grpc_lro_async_client(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_ca_pool_path(): + project = "squid" + location = "clam" + ca_pool = "whelk" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}".format( + project=project, + location=location, + ca_pool=ca_pool, + ) + actual = CertificateAuthorityServiceClient.ca_pool_path(project, location, ca_pool) + assert expected == actual + + +def test_parse_ca_pool_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ca_pool": "nudibranch", + } + path = CertificateAuthorityServiceClient.ca_pool_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_ca_pool_path(path) + assert expected == actual + + +def test_certificate_path(): + project = "cuttlefish" + location = "mussel" + ca_pool = "winkle" + certificate = "nautilus" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificates/{certificate}".format( + project=project, + location=location, + ca_pool=ca_pool, + certificate=certificate, + ) + actual = CertificateAuthorityServiceClient.certificate_path( + project, location, ca_pool, certificate + ) + assert expected == actual + + +def test_parse_certificate_path(): + expected = { + "project": "scallop", + "location": "abalone", + "ca_pool": "squid", + "certificate": "clam", + } + path = CertificateAuthorityServiceClient.certificate_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_path(path) + assert expected == actual + + +def test_certificate_authority_path(): + project = "whelk" + location = "octopus" + ca_pool = "oyster" + certificate_authority = "nudibranch" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}".format( + project=project, + location=location, + ca_pool=ca_pool, + certificate_authority=certificate_authority, + ) + actual = CertificateAuthorityServiceClient.certificate_authority_path( + project, location, ca_pool, certificate_authority + ) + assert expected == actual + + +def test_parse_certificate_authority_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "ca_pool": "winkle", + "certificate_authority": "nautilus", + } + path = CertificateAuthorityServiceClient.certificate_authority_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_authority_path(path) + assert expected == actual + + +def test_certificate_revocation_list_path(): + project = "scallop" + location = "abalone" + ca_pool = "squid" + certificate_authority = "clam" + certificate_revocation_list = "whelk" + expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}/certificateRevocationLists/{certificate_revocation_list}".format( + project=project, + location=location, + ca_pool=ca_pool, + certificate_authority=certificate_authority, + certificate_revocation_list=certificate_revocation_list, + ) + actual = CertificateAuthorityServiceClient.certificate_revocation_list_path( + project, location, ca_pool, certificate_authority, certificate_revocation_list + ) + assert expected == actual + + +def test_parse_certificate_revocation_list_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ca_pool": "nudibranch", + "certificate_authority": "cuttlefish", + "certificate_revocation_list": "mussel", + } + path = CertificateAuthorityServiceClient.certificate_revocation_list_path( + **expected + ) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_revocation_list_path( + path + ) + assert expected == actual + + +def test_certificate_template_path(): + project = "winkle" + location = "nautilus" + certificate_template = "scallop" + expected = "projects/{project}/locations/{location}/certificateTemplates/{certificate_template}".format( + project=project, + location=location, + certificate_template=certificate_template, + ) + actual = CertificateAuthorityServiceClient.certificate_template_path( + project, location, certificate_template + ) + assert expected == actual + + +def test_parse_certificate_template_path(): + expected = { + "project": "abalone", + "location": "squid", + "certificate_template": "clam", + } + path = CertificateAuthorityServiceClient.certificate_template_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_certificate_template_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CertificateAuthorityServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = CertificateAuthorityServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = CertificateAuthorityServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = CertificateAuthorityServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CertificateAuthorityServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = CertificateAuthorityServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format( + project=project, + ) + actual = CertificateAuthorityServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = CertificateAuthorityServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = CertificateAuthorityServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = CertificateAuthorityServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CertificateAuthorityServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CertificateAuthorityServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.ListLocationsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"resource": "projects/sample1/locations/sample2/caPools/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"resource": "projects/sample1/locations/sample2/caPools/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = iam_policy_pb2.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: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_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 = iam_policy_pb2.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: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + 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: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + # 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: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + await client.set_iam_policy(request) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - 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 + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_certificate_authority_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) +def test_set_iam_policy_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_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 = policy_pb2.Policy() - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - 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 + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() -def test_certificate_authority_service_grpc_lro_client(): - client = CertificateAuthorityServiceClient( +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - transport = client.transport + # 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_pb2.Policy()) - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # 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 = iam_policy_pb2.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: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) -def test_certificate_authority_service_grpc_lro_async_client(): + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = CertificateAuthorityServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + transport=transport, ) - transport = client.transport - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) + # 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 = iam_policy_pb2.GetIamPolicyRequest() - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # 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_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.get_iam_policy(request) -def test_ca_pool_path(): - project = "squid" - location = "clam" - ca_pool = "whelk" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}".format( - project=project, - location=location, - ca_pool=ca_pool, - ) - actual = CertificateAuthorityServiceClient.ca_pool_path(project, location, ca_pool) - assert expected == actual + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_parse_ca_pool_path(): - expected = { - "project": "octopus", - "location": "oyster", - "ca_pool": "nudibranch", - } - path = CertificateAuthorityServiceClient.ca_pool_path(**expected) + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_ca_pool_path(path) - assert expected == actual + assert response.version == 774 + assert response.etag == b"etag_blob" -def test_certificate_path(): - project = "cuttlefish" - location = "mussel" - ca_pool = "winkle" - certificate = "nautilus" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificates/{certificate}".format( - project=project, - location=location, - ca_pool=ca_pool, - certificate=certificate, - ) - actual = CertificateAuthorityServiceClient.certificate_path( - project, location, ca_pool, certificate + +def test_get_iam_policy_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" -def test_parse_certificate_path(): - expected = { - "project": "scallop", - "location": "abalone", - "ca_pool": "squid", - "certificate": "clam", - } - path = CertificateAuthorityServiceClient.certificate_path(**expected) + # 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: + call.return_value = policy_pb2.Policy() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_path(path) - assert expected == actual + client.get_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_certificate_authority_path(): - project = "whelk" - location = "octopus" - ca_pool = "oyster" - certificate_authority = "nudibranch" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}".format( - project=project, - location=location, - ca_pool=ca_pool, - certificate_authority=certificate_authority, - ) - actual = CertificateAuthorityServiceClient.certificate_authority_path( - project, location, ca_pool, certificate_authority + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" -def test_parse_certificate_authority_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "ca_pool": "winkle", - "certificate_authority": "nautilus", - } - path = CertificateAuthorityServiceClient.certificate_authority_path(**expected) + # 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: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_authority_path(path) - assert expected == actual + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] -def test_certificate_revocation_list_path(): - project = "scallop" - location = "abalone" - ca_pool = "squid" - certificate_authority = "clam" - certificate_revocation_list = "whelk" - expected = "projects/{project}/locations/{location}/caPools/{ca_pool}/certificateAuthorities/{certificate_authority}/certificateRevocationLists/{certificate_revocation_list}".format( - project=project, - location=location, - ca_pool=ca_pool, - certificate_authority=certificate_authority, - certificate_revocation_list=certificate_revocation_list, - ) - actual = CertificateAuthorityServiceClient.certificate_revocation_list_path( - project, location, ca_pool, certificate_authority, certificate_revocation_list +def test_get_iam_policy_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # 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 = policy_pb2.Policy() + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() -def test_parse_certificate_revocation_list_path(): - expected = { - "project": "octopus", - "location": "oyster", - "ca_pool": "nudibranch", - "certificate_authority": "cuttlefish", - "certificate_revocation_list": "mussel", - } - path = CertificateAuthorityServiceClient.certificate_revocation_list_path( - **expected - ) - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_revocation_list_path( - path +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # 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_pb2.Policy()) + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() -def test_certificate_template_path(): - project = "winkle" - location = "nautilus" - certificate_template = "scallop" - expected = "projects/{project}/locations/{location}/certificateTemplates/{certificate_template}".format( - project=project, - location=location, - certificate_template=certificate_template, - ) - actual = CertificateAuthorityServiceClient.certificate_template_path( - project, location, certificate_template - ) - assert expected == actual +def test_test_iam_permissions(transport: str = "grpc"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_parse_certificate_template_path(): - expected = { - "project": "abalone", - "location": "squid", - "certificate_template": "clam", - } - path = CertificateAuthorityServiceClient.certificate_template_path(**expected) + # 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 = iam_policy_pb2.TestIamPermissionsRequest() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_certificate_template_path(path) - assert expected == actual + # 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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + response = client.test_iam_permissions(request) -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = CertificateAuthorityServiceClient.common_billing_account_path( - billing_account - ) - assert expected == actual + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = CertificateAuthorityServiceClient.common_billing_account_path(**expected) + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_billing_account_path(path) - assert expected == actual + assert response.permissions == ["permissions_value"] -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format( - folder=folder, +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = CertificateAuthorityServiceClient.common_folder_path(folder) - assert expected == actual + # 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 = iam_policy_pb2.TestIamPermissionsRequest() -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = CertificateAuthorityServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_folder_path(path) - assert expected == actual + # 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_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + response = await client.test_iam_permissions(request) -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format( - organization=organization, - ) - actual = CertificateAuthorityServiceClient.common_organization_path(organization) - assert expected == actual + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = CertificateAuthorityServiceClient.common_organization_path(**expected) + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_organization_path(path) - assert expected == actual + assert response.permissions == ["permissions_value"] -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, +def test_test_iam_permissions_field_headers(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = CertificateAuthorityServiceClient.common_project_path(project) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = CertificateAuthorityServiceClient.common_project_path(**expected) + # 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: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_project_path(path) - assert expected == actual + client.test_iam_permissions(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = CertificateAuthorityServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = CertificateAuthorityServiceClient.common_location_path(project, location) - assert expected == actual + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # 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: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = CertificateAuthorityServiceClient.common_location_path(**expected) + await client.test_iam_permissions(request) - # Check that the path construction is reversible. - actual = CertificateAuthorityServiceClient.parse_common_location_path(path) - assert expected == actual + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() +def test_test_iam_permissions_from_dict(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - with mock.patch.object( - transports.CertificateAuthorityServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = CertificateAuthorityServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } ) - prep.assert_called_once_with(client_info) + call.assert_called() @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_test_iam_permissions_from_dict_async(): client = CertificateAuthorityServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + 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_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -9821,6 +22458,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py b/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py index 6febcb4..af7a3b9 100644 --- a/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py +++ b/tests/unit/gapic/privateca_v1beta1/test_certificate_authority_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import ( @@ -43,6 +45,7 @@ from google.oauth2 import service_account from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore import grpc @@ -50,6 +53,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.security.privateca_v1beta1.services.certificate_authority_service import ( CertificateAuthorityServiceAsyncClient, @@ -112,6 +117,7 @@ def test__get_default_mtls_endpoint(): [ (CertificateAuthorityServiceClient, "grpc"), (CertificateAuthorityServiceAsyncClient, "grpc_asyncio"), + (CertificateAuthorityServiceClient, "rest"), ], ) def test_certificate_authority_service_client_from_service_account_info( @@ -127,7 +133,11 @@ def test_certificate_authority_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("privateca.googleapis.com:443") + assert client.transport._host == ( + "privateca.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com" + ) @pytest.mark.parametrize( @@ -135,6 +145,7 @@ def test_certificate_authority_service_client_from_service_account_info( [ (transports.CertificateAuthorityServiceGrpcTransport, "grpc"), (transports.CertificateAuthorityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CertificateAuthorityServiceRestTransport, "rest"), ], ) def test_certificate_authority_service_client_service_account_always_use_jwt( @@ -160,6 +171,7 @@ def test_certificate_authority_service_client_service_account_always_use_jwt( [ (CertificateAuthorityServiceClient, "grpc"), (CertificateAuthorityServiceAsyncClient, "grpc_asyncio"), + (CertificateAuthorityServiceClient, "rest"), ], ) def test_certificate_authority_service_client_from_service_account_file( @@ -182,13 +194,18 @@ def test_certificate_authority_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("privateca.googleapis.com:443") + assert client.transport._host == ( + "privateca.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com" + ) def test_certificate_authority_service_client_get_transport_class(): transport = CertificateAuthorityServiceClient.get_transport_class() available_transports = [ transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceRestTransport, ] assert transport in available_transports @@ -209,6 +226,11 @@ def test_certificate_authority_service_client_get_transport_class(): transports.CertificateAuthorityServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -368,6 +390,18 @@ def test_certificate_authority_service_client_client_options( "grpc_asyncio", "false", ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + "true", + ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -574,6 +608,11 @@ def test_certificate_authority_service_client_get_mtls_endpoint_and_cert_source( transports.CertificateAuthorityServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + ), ], ) def test_certificate_authority_service_client_client_options_scopes( @@ -614,6 +653,12 @@ def test_certificate_authority_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + CertificateAuthorityServiceClient, + transports.CertificateAuthorityServiceRestTransport, + "rest", + None, + ), ], ) def test_certificate_authority_service_client_client_options_credentials_file( @@ -6552,141 +6597,7267 @@ async def test_list_reusable_configs_async_pages(): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateRequest, + dict, + ], +) +def test_create_certificate_rest(request_type): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request_init["certificate"] = { + "name": "name_value", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_create_certificate_rest_required_fields( + request_type=service.CreateCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "certificate_id", + "request_id", ) + ) + jsonified_request.update(unset_fields) - # It is an error to provide an api_key and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options=options, - transport=transport, - ) + request = request_type(**request_init) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "certificateId", + "requestId", + ) + ) + & set( + ( + "parent", + "certificate", + ) ) + ) - # It is an error to provide scopes and a transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = CertificateAuthorityServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_create_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_create_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateRequest.pb( + service.CreateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() ) + request = service.CreateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( + client.create_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_rest_bad_request( + transport: str = "rest", request_type=service.CreateCertificateRequest +): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = CertificateAuthorityServiceClient(transport=transport) - assert client.transport is transport + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request_init["certificate"] = { + "name": "name_value", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate(request) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CertificateAuthorityServiceGrpcTransport( +def test_create_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + certificate=resources.Certificate(name="name_value"), + certificate_id="certificate_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_certificate( + service.CreateCertificateRequest(), + parent="parent_value", + certificate=resources.Certificate(name="name_value"), + certificate_id="certificate_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CertificateAuthorityServiceGrpcTransport, - transports.CertificateAuthorityServiceGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_create_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + service.GetCertificateRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = CertificateAuthorityServiceClient.get_transport_class(transport_name)( +def test_get_certificate_rest(request_type): + client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_get_certificate_rest_required_fields( + request_type=service.GetCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = CertificateAuthorityServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.CertificateAuthorityServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_certificate_authority_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CertificateAuthorityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_get_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_get_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateRequest.pb(service.GetCertificateRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() ) + request = service.GetCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() -def test_certificate_authority_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.security.privateca_v1beta1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CertificateAuthorityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.get_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_rest_bad_request( + transport: str = "rest", request_type=service.GetCertificateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate(request) + + +def test_get_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_certificate( + service.GetCertificateRequest(), + name="name_value", + ) + + +def test_get_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificatesRequest, + dict, + ], +) +def test_list_certificates_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificates_rest_required_fields( + request_type=service.ListCertificatesRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificates._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificates._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificatesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificates(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificates_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificates._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificates_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_list_certificates" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_list_certificates" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificatesRequest.pb( + service.ListCertificatesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCertificatesResponse.to_json( + service.ListCertificatesResponse() + ) + + request = service.ListCertificatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificatesResponse() + + client.list_certificates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificates_rest_bad_request( + transport: str = "rest", request_type=service.ListCertificatesRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificates(request) + + +def test_list_certificates_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificatesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificates(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificates" + % client.transport._host, + args[1], + ) + + +def test_list_certificates_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificates( + service.ListCertificatesRequest(), + parent="parent_value", + ) + + +def test_list_certificates_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + resources.Certificate(), + resources.Certificate(), + ], + next_page_token="abc", + ), + service.ListCertificatesResponse( + certificates=[], + next_page_token="def", + ), + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + ], + next_page_token="ghi", + ), + service.ListCertificatesResponse( + certificates=[ + resources.Certificate(), + resources.Certificate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListCertificatesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + pager = client.list_certificates(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Certificate) for i in results) + + pages = list(client.list_certificates(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.RevokeCertificateRequest, + dict, + ], +) +def test_revoke_certificate_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.revoke_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_revoke_certificate_rest_required_fields( + request_type=service.RevokeCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).revoke_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).revoke_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.revoke_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_revoke_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.revoke_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "reason", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_revoke_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_revoke_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_revoke_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RevokeCertificateRequest.pb( + service.RevokeCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() + ) + + request = service.RevokeCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.revoke_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_revoke_certificate_rest_bad_request( + transport: str = "rest", request_type=service.RevokeCertificateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.revoke_certificate(request) + + +def test_revoke_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.revoke_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificates/*}:revoke" + % client.transport._host, + args[1], + ) + + +def test_revoke_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.revoke_certificate( + service.RevokeCertificateRequest(), + name="name_value", + ) + + +def test_revoke_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateRequest, + dict, + ], +) +def test_update_certificate_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate( + name="name_value", + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Certificate) + assert response.name == "name_value" + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + + +def test_update_certificate_rest_required_fields( + request_type=service.UpdateCertificateRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificate", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "post_update_certificate" + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_update_certificate" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateRequest.pb( + service.UpdateCertificateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Certificate.to_json( + resources.Certificate() + ) + + request = service.UpdateCertificateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Certificate() + + client.update_certificate( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCertificateRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + } + request_init["certificate"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4", + "pem_csr": "pem_csr_value", + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "revocation_details": { + "revocation_state": 1, + "revocation_time": {"seconds": 751, "nanos": 543}, + }, + "pem_certificate": "pem_certificate_value", + "certificate_description": { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + }, + "pem_certificate_chain": [ + "pem_certificate_chain_value1", + "pem_certificate_chain_value2", + ], + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate(request) + + +def test_update_certificate_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Certificate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificates/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate=resources.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Certificate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{certificate.name=projects/*/locations/*/certificateAuthorities/*/certificates/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate( + service.UpdateCertificateRequest(), + certificate=resources.Certificate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ActivateCertificateAuthorityRequest, + dict, + ], +) +def test_activate_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.activate_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_activate_certificate_authority_rest_required_fields( + request_type=service.ActivateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["pem_ca_certificate"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).activate_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["pemCaCertificate"] = "pem_ca_certificate_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).activate_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "pemCaCertificate" in jsonified_request + assert jsonified_request["pemCaCertificate"] == "pem_ca_certificate_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.activate_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_activate_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.activate_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "pemCaCertificate", + "subordinateConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_activate_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_activate_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_activate_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ActivateCertificateAuthorityRequest.pb( + service.ActivateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.ActivateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.activate_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_activate_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.ActivateCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.activate_certificate_authority(request) + + +def test_activate_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.activate_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:activate" + % client.transport._host, + args[1], + ) + + +def test_activate_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.activate_certificate_authority( + service.ActivateCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_activate_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateCertificateAuthorityRequest, + dict, + ], +) +def test_create_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_authority"] = { + "name": "name_value", + "type_": 1, + "tier": 1, + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "certificate_policy": { + "allowed_config_list": {"allowed_config_values": {}}, + "overwrite_config_values": {}, + "allowed_locations_and_organizations": {}, + "allowed_common_names": [ + "allowed_common_names_value1", + "allowed_common_names_value2", + ], + "allowed_sans": { + "allowed_dns_names": [ + "allowed_dns_names_value1", + "allowed_dns_names_value2", + ], + "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], + "allowed_email_addresses": [ + "allowed_email_addresses_value1", + "allowed_email_addresses_value2", + ], + "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], + "allow_globbing_dns_wildcards": True, + "allow_custom_sans": True, + }, + "maximum_lifetime": {}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + }, + "issuing_options": { + "include_ca_cert_url": True, + "include_crl_access_url": True, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_url": "crl_access_url_value", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_certificate_authority_rest_required_fields( + request_type=service.CreateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["certificate_authority_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "certificateAuthorityId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "certificateAuthorityId" in jsonified_request + assert ( + jsonified_request["certificateAuthorityId"] + == request_init["certificate_authority_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["certificateAuthorityId"] = "certificate_authority_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_certificate_authority._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "certificate_authority_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "certificateAuthorityId" in jsonified_request + assert ( + jsonified_request["certificateAuthorityId"] == "certificate_authority_id_value" + ) + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_certificate_authority(request) + + expected_params = [ + ( + "certificateAuthorityId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "certificateAuthorityId", + "requestId", + ) + ) + & set( + ( + "parent", + "certificateAuthorityId", + "certificateAuthority", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_create_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_create_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCertificateAuthorityRequest.pb( + service.CreateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.CreateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.CreateCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["certificate_authority"] = { + "name": "name_value", + "type_": 1, + "tier": 1, + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "certificate_policy": { + "allowed_config_list": {"allowed_config_values": {}}, + "overwrite_config_values": {}, + "allowed_locations_and_organizations": {}, + "allowed_common_names": [ + "allowed_common_names_value1", + "allowed_common_names_value2", + ], + "allowed_sans": { + "allowed_dns_names": [ + "allowed_dns_names_value1", + "allowed_dns_names_value2", + ], + "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], + "allowed_email_addresses": [ + "allowed_email_addresses_value1", + "allowed_email_addresses_value2", + ], + "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], + "allow_globbing_dns_wildcards": True, + "allow_custom_sans": True, + }, + "maximum_lifetime": {}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + }, + "issuing_options": { + "include_ca_cert_url": True, + "include_crl_access_url": True, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_url": "crl_access_url_value", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_certificate_authority(request) + + +def test_create_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + certificate_authority=resources.CertificateAuthority(name="name_value"), + certificate_authority_id="certificate_authority_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities" + % client.transport._host, + args[1], + ) + + +def test_create_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_certificate_authority( + service.CreateCertificateAuthorityRequest(), + parent="parent_value", + certificate_authority=resources.CertificateAuthority(name="name_value"), + certificate_authority_id="certificate_authority_id_value", + ) + + +def test_create_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DisableCertificateAuthorityRequest, + dict, + ], +) +def test_disable_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.disable_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_disable_certificate_authority_rest_required_fields( + request_type=service.DisableCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.disable_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_disable_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.disable_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_disable_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_disable_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DisableCertificateAuthorityRequest.pb( + service.DisableCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.DisableCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.disable_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_disable_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.DisableCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.disable_certificate_authority(request) + + +def test_disable_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.disable_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:disable" + % client.transport._host, + args[1], + ) + + +def test_disable_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.disable_certificate_authority( + service.DisableCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_disable_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.EnableCertificateAuthorityRequest, + dict, + ], +) +def test_enable_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.enable_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_enable_certificate_authority_rest_required_fields( + request_type=service.EnableCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.enable_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_enable_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.enable_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enable_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_enable_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_enable_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.EnableCertificateAuthorityRequest.pb( + service.EnableCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.EnableCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.enable_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_enable_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.EnableCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.enable_certificate_authority(request) + + +def test_enable_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.enable_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:enable" + % client.transport._host, + args[1], + ) + + +def test_enable_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.enable_certificate_authority( + service.EnableCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_enable_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.FetchCertificateAuthorityCsrRequest, + dict, + ], +) +def test_fetch_certificate_authority_csr_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.FetchCertificateAuthorityCsrResponse( + pem_csr="pem_csr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.fetch_certificate_authority_csr(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.FetchCertificateAuthorityCsrResponse) + assert response.pem_csr == "pem_csr_value" + + +def test_fetch_certificate_authority_csr_rest_required_fields( + request_type=service.FetchCertificateAuthorityCsrRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_certificate_authority_csr._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).fetch_certificate_authority_csr._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.FetchCertificateAuthorityCsrResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.FetchCertificateAuthorityCsrResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.fetch_certificate_authority_csr(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_fetch_certificate_authority_csr_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.fetch_certificate_authority_csr._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_certificate_authority_csr_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_fetch_certificate_authority_csr", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_fetch_certificate_authority_csr", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FetchCertificateAuthorityCsrRequest.pb( + service.FetchCertificateAuthorityCsrRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + service.FetchCertificateAuthorityCsrResponse.to_json( + service.FetchCertificateAuthorityCsrResponse() + ) + ) + + request = service.FetchCertificateAuthorityCsrRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.FetchCertificateAuthorityCsrResponse() + + client.fetch_certificate_authority_csr( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_certificate_authority_csr_rest_bad_request( + transport: str = "rest", request_type=service.FetchCertificateAuthorityCsrRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.fetch_certificate_authority_csr(request) + + +def test_fetch_certificate_authority_csr_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.FetchCertificateAuthorityCsrResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.FetchCertificateAuthorityCsrResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.fetch_certificate_authority_csr(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:fetch" + % client.transport._host, + args[1], + ) + + +def test_fetch_certificate_authority_csr_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_certificate_authority_csr( + service.FetchCertificateAuthorityCsrRequest(), + name="name_value", + ) + + +def test_fetch_certificate_authority_csr_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateAuthorityRequest, + dict, + ], +) +def test_get_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateAuthority( + name="name_value", + type_=resources.CertificateAuthority.Type.SELF_SIGNED, + tier=resources.CertificateAuthority.Tier.ENTERPRISE, + state=resources.CertificateAuthority.State.ENABLED, + pem_ca_certificates=["pem_ca_certificates_value"], + gcs_bucket="gcs_bucket_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateAuthority) + assert response.name == "name_value" + assert response.type_ == resources.CertificateAuthority.Type.SELF_SIGNED + assert response.tier == resources.CertificateAuthority.Tier.ENTERPRISE + assert response.state == resources.CertificateAuthority.State.ENABLED + assert response.pem_ca_certificates == ["pem_ca_certificates_value"] + assert response.gcs_bucket == "gcs_bucket_value" + + +def test_get_certificate_authority_rest_required_fields( + request_type=service.GetCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CertificateAuthority() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateAuthorityRequest.pb( + service.GetCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.CertificateAuthority.to_json( + resources.CertificateAuthority() + ) + + request = service.GetCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateAuthority() + + client.get_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.GetCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_authority(request) + + +def test_get_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateAuthority() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateAuthority.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_certificate_authority( + service.GetCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_get_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateAuthoritiesRequest, + dict, + ], +) +def test_list_certificate_authorities_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_authorities(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateAuthoritiesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_authorities_rest_required_fields( + request_type=service.ListCertificateAuthoritiesRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_authorities._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_authorities._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCertificateAuthoritiesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_authorities(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_authorities_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_certificate_authorities._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_authorities_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_authorities", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_authorities", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateAuthoritiesRequest.pb( + service.ListCertificateAuthoritiesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListCertificateAuthoritiesResponse.to_json( + service.ListCertificateAuthoritiesResponse() + ) + + request = service.ListCertificateAuthoritiesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateAuthoritiesResponse() + + client.list_certificate_authorities( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_authorities_rest_bad_request( + transport: str = "rest", request_type=service.ListCertificateAuthoritiesRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_authorities(request) + + +def test_list_certificate_authorities_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateAuthoritiesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateAuthoritiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_authorities(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/certificateAuthorities" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_authorities_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificate_authorities( + service.ListCertificateAuthoritiesRequest(), + parent="parent_value", + ) + + +def test_list_certificate_authorities_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + resources.CertificateAuthority(), + resources.CertificateAuthority(), + ], + next_page_token="abc", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[], + next_page_token="def", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + ], + next_page_token="ghi", + ), + service.ListCertificateAuthoritiesResponse( + certificate_authorities=[ + resources.CertificateAuthority(), + resources.CertificateAuthority(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCertificateAuthoritiesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_certificate_authorities(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CertificateAuthority) for i in results) + + pages = list(client.list_certificate_authorities(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.RestoreCertificateAuthorityRequest, + dict, + ], +) +def test_restore_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.restore_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_restore_certificate_authority_rest_required_fields( + request_type=service.RestoreCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.restore_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_restore_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restore_certificate_authority._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_restore_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_restore_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestoreCertificateAuthorityRequest.pb( + service.RestoreCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.RestoreCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.restore_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.RestoreCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.restore_certificate_authority(request) + + +def test_restore_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.restore_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_certificate_authority( + service.RestoreCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_restore_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ScheduleDeleteCertificateAuthorityRequest, + dict, + ], +) +def test_schedule_delete_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.schedule_delete_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_schedule_delete_certificate_authority_rest_required_fields( + request_type=service.ScheduleDeleteCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).schedule_delete_certificate_authority._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).schedule_delete_certificate_authority._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.schedule_delete_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_schedule_delete_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.schedule_delete_certificate_authority._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_schedule_delete_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_schedule_delete_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_schedule_delete_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ScheduleDeleteCertificateAuthorityRequest.pb( + service.ScheduleDeleteCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.ScheduleDeleteCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.schedule_delete_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_schedule_delete_certificate_authority_rest_bad_request( + transport: str = "rest", + request_type=service.ScheduleDeleteCertificateAuthorityRequest, +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.schedule_delete_certificate_authority(request) + + +def test_schedule_delete_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.schedule_delete_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*}:scheduleDelete" + % client.transport._host, + args[1], + ) + + +def test_schedule_delete_certificate_authority_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.schedule_delete_certificate_authority( + service.ScheduleDeleteCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_schedule_delete_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateAuthorityRequest, + dict, + ], +) +def test_update_certificate_authority_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + } + request_init["certificate_authority"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3", + "type_": 1, + "tier": 1, + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "certificate_policy": { + "allowed_config_list": {"allowed_config_values": {}}, + "overwrite_config_values": {}, + "allowed_locations_and_organizations": {}, + "allowed_common_names": [ + "allowed_common_names_value1", + "allowed_common_names_value2", + ], + "allowed_sans": { + "allowed_dns_names": [ + "allowed_dns_names_value1", + "allowed_dns_names_value2", + ], + "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], + "allowed_email_addresses": [ + "allowed_email_addresses_value1", + "allowed_email_addresses_value2", + ], + "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], + "allow_globbing_dns_wildcards": True, + "allow_custom_sans": True, + }, + "maximum_lifetime": {}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + }, + "issuing_options": { + "include_ca_cert_url": True, + "include_crl_access_url": True, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_url": "crl_access_url_value", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_authority_rest_required_fields( + request_type=service.UpdateCertificateAuthorityRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_authority._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_authority_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificateAuthority", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_authority", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_authority", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateAuthorityRequest.pb( + service.UpdateCertificateAuthorityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_authority_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCertificateAuthorityRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + } + request_init["certificate_authority"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3", + "type_": 1, + "tier": 1, + "config": { + "subject_config": { + "subject": { + "country_code": "country_code_value", + "organization": "organization_value", + "organizational_unit": "organizational_unit_value", + "locality": "locality_value", + "province": "province_value", + "street_address": "street_address_value", + "postal_code": "postal_code_value", + }, + "common_name": "common_name_value", + "subject_alt_name": { + "dns_names": ["dns_names_value1", "dns_names_value2"], + "uris": ["uris_value1", "uris_value2"], + "email_addresses": [ + "email_addresses_value1", + "email_addresses_value2", + ], + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "custom_sans": [ + { + "object_id": {"object_id_path": [1456, 1457]}, + "critical": True, + "value": b"value_blob", + } + ], + }, + }, + "reusable_config": { + "reusable_config": "reusable_config_value", + "reusable_config_values": { + "key_usage": { + "base_key_usage": { + "digital_signature": True, + "content_commitment": True, + "key_encipherment": True, + "data_encipherment": True, + "key_agreement": True, + "cert_sign": True, + "crl_sign": True, + "encipher_only": True, + "decipher_only": True, + }, + "extended_key_usage": { + "server_auth": True, + "client_auth": True, + "code_signing": True, + "email_protection": True, + "time_stamping": True, + "ocsp_signing": True, + }, + "unknown_extended_key_usages": {}, + }, + "ca_options": { + "is_ca": {"value": True}, + "max_issuer_path_length": {"value": 541}, + }, + "policy_ids": {}, + "aia_ocsp_servers": [ + "aia_ocsp_servers_value1", + "aia_ocsp_servers_value2", + ], + "additional_extensions": {}, + }, + }, + "public_key": {"type_": 1, "key": b"key_blob"}, + }, + "lifetime": {"seconds": 751, "nanos": 543}, + "key_spec": { + "cloud_kms_key_version": "cloud_kms_key_version_value", + "algorithm": 1, + }, + "certificate_policy": { + "allowed_config_list": {"allowed_config_values": {}}, + "overwrite_config_values": {}, + "allowed_locations_and_organizations": {}, + "allowed_common_names": [ + "allowed_common_names_value1", + "allowed_common_names_value2", + ], + "allowed_sans": { + "allowed_dns_names": [ + "allowed_dns_names_value1", + "allowed_dns_names_value2", + ], + "allowed_uris": ["allowed_uris_value1", "allowed_uris_value2"], + "allowed_email_addresses": [ + "allowed_email_addresses_value1", + "allowed_email_addresses_value2", + ], + "allowed_ips": ["allowed_ips_value1", "allowed_ips_value2"], + "allow_globbing_dns_wildcards": True, + "allow_custom_sans": True, + }, + "maximum_lifetime": {}, + "allowed_issuance_modes": { + "allow_csr_based_issuance": True, + "allow_config_based_issuance": True, + }, + }, + "issuing_options": { + "include_ca_cert_url": True, + "include_crl_access_url": True, + }, + "subordinate_config": { + "certificate_authority": "certificate_authority_value", + "pem_issuer_chain": { + "pem_certificates": [ + "pem_certificates_value1", + "pem_certificates_value2", + ] + }, + }, + "state": 1, + "pem_ca_certificates": [ + "pem_ca_certificates_value1", + "pem_ca_certificates_value2", + ], + "ca_certificate_descriptions": [ + { + "subject_description": { + "subject": {}, + "common_name": "common_name_value", + "subject_alt_name": {}, + "hex_serial_number": "hex_serial_number_value", + "lifetime": {}, + "not_before_time": {"seconds": 751, "nanos": 543}, + "not_after_time": {}, + }, + "config_values": {}, + "public_key": {}, + "subject_key_id": {"key_id": "key_id_value"}, + "authority_key_id": {}, + "crl_distribution_points": [ + "crl_distribution_points_value1", + "crl_distribution_points_value2", + ], + "aia_issuing_certificate_urls": [ + "aia_issuing_certificate_urls_value1", + "aia_issuing_certificate_urls_value2", + ], + "cert_fingerprint": {"sha256_hash": "sha256_hash_value"}, + } + ], + "gcs_bucket": "gcs_bucket_value", + "access_urls": { + "ca_certificate_access_url": "ca_certificate_access_url_value", + "crl_access_url": "crl_access_url_value", + }, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate_authority(request) + + +def test_update_certificate_authority_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_authority": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_authority=resources.CertificateAuthority(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_authority(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{certificate_authority.name=projects/*/locations/*/certificateAuthorities/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate_authority( + service.UpdateCertificateAuthorityRequest(), + certificate_authority=resources.CertificateAuthority(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_authority_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetCertificateRevocationListRequest, + dict, + ], +) +def test_get_certificate_revocation_list_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateRevocationList( + name="name_value", + sequence_number=1601, + pem_crl="pem_crl_value", + access_url="access_url_value", + state=resources.CertificateRevocationList.State.ACTIVE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_certificate_revocation_list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CertificateRevocationList) + assert response.name == "name_value" + assert response.sequence_number == 1601 + assert response.pem_crl == "pem_crl_value" + assert response.access_url == "access_url_value" + assert response.state == resources.CertificateRevocationList.State.ACTIVE + + +def test_get_certificate_revocation_list_rest_required_fields( + request_type=service.GetCertificateRevocationListRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_revocation_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_revocation_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CertificateRevocationList() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_certificate_revocation_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_certificate_revocation_list_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_revocation_list._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_revocation_list_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_get_certificate_revocation_list", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_get_certificate_revocation_list", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCertificateRevocationListRequest.pb( + service.GetCertificateRevocationListRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.CertificateRevocationList.to_json( + resources.CertificateRevocationList() + ) + + request = service.GetCertificateRevocationListRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CertificateRevocationList() + + client.get_certificate_revocation_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_certificate_revocation_list_rest_bad_request( + transport: str = "rest", request_type=service.GetCertificateRevocationListRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_certificate_revocation_list(request) + + +def test_get_certificate_revocation_list_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CertificateRevocationList() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.CertificateRevocationList.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_certificate_revocation_list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_revocation_list_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_certificate_revocation_list( + service.GetCertificateRevocationListRequest(), + name="name_value", + ) + + +def test_get_certificate_revocation_list_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListCertificateRevocationListsRequest, + dict, + ], +) +def test_list_certificate_revocation_lists_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateRevocationListsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateRevocationListsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_certificate_revocation_lists(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCertificateRevocationListsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_certificate_revocation_lists_rest_required_fields( + request_type=service.ListCertificateRevocationListsRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_revocation_lists._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_certificate_revocation_lists._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateRevocationListsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListCertificateRevocationListsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_certificate_revocation_lists(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_certificate_revocation_lists_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_certificate_revocation_lists._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_certificate_revocation_lists_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_list_certificate_revocation_lists", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_certificate_revocation_lists", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCertificateRevocationListsRequest.pb( + service.ListCertificateRevocationListsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + service.ListCertificateRevocationListsResponse.to_json( + service.ListCertificateRevocationListsResponse() + ) + ) + + request = service.ListCertificateRevocationListsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCertificateRevocationListsResponse() + + client.list_certificate_revocation_lists( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_certificate_revocation_lists_rest_bad_request( + transport: str = "rest", request_type=service.ListCertificateRevocationListsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_certificate_revocation_lists(request) + + +def test_list_certificate_revocation_lists_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCertificateRevocationListsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListCertificateRevocationListsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_certificate_revocation_lists(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*/certificateAuthorities/*}/certificateRevocationLists" + % client.transport._host, + args[1], + ) + + +def test_list_certificate_revocation_lists_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_certificate_revocation_lists( + service.ListCertificateRevocationListsRequest(), + parent="parent_value", + ) + + +def test_list_certificate_revocation_lists_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + ], + next_page_token="abc", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[], + next_page_token="def", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + ], + next_page_token="ghi", + ), + service.ListCertificateRevocationListsResponse( + certificate_revocation_lists=[ + resources.CertificateRevocationList(), + resources.CertificateRevocationList(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListCertificateRevocationListsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/certificateAuthorities/sample3" + } + + pager = client.list_certificate_revocation_lists(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CertificateRevocationList) for i in results) + + pages = list( + client.list_certificate_revocation_lists(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateCertificateRevocationListRequest, + dict, + ], +) +def test_update_certificate_revocation_list_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + } + request_init["certificate_revocation_list"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4", + "sequence_number": 1601, + "revoked_certificates": [ + { + "certificate": "certificate_value", + "hex_serial_number": "hex_serial_number_value", + "revocation_reason": 1, + } + ], + "pem_crl": "pem_crl_value", + "access_url": "access_url_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_certificate_revocation_list(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_certificate_revocation_list_rest_required_fields( + request_type=service.UpdateCertificateRevocationListRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_revocation_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_certificate_revocation_list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_certificate_revocation_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_certificate_revocation_list_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_certificate_revocation_list._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "certificateRevocationList", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_certificate_revocation_list_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_update_certificate_revocation_list", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_update_certificate_revocation_list", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCertificateRevocationListRequest.pb( + service.UpdateCertificateRevocationListRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = service.UpdateCertificateRevocationListRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_certificate_revocation_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_certificate_revocation_list_rest_bad_request( + transport: str = "rest", request_type=service.UpdateCertificateRevocationListRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + } + request_init["certificate_revocation_list"] = { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4", + "sequence_number": 1601, + "revoked_certificates": [ + { + "certificate": "certificate_value", + "hex_serial_number": "hex_serial_number_value", + "revocation_reason": 1, + } + ], + "pem_crl": "pem_crl_value", + "access_url": "access_url_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_certificate_revocation_list(request) + + +def test_update_certificate_revocation_list_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "certificate_revocation_list": { + "name": "projects/sample1/locations/sample2/certificateAuthorities/sample3/certificateRevocationLists/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + certificate_revocation_list=resources.CertificateRevocationList( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_certificate_revocation_list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{certificate_revocation_list.name=projects/*/locations/*/certificateAuthorities/*/certificateRevocationLists/*}" + % client.transport._host, + args[1], + ) + + +def test_update_certificate_revocation_list_rest_flattened_error( + transport: str = "rest", +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_certificate_revocation_list( + service.UpdateCertificateRevocationListRequest(), + certificate_revocation_list=resources.CertificateRevocationList( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_certificate_revocation_list_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetReusableConfigRequest, + dict, + ], +) +def test_get_reusable_config_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/reusableConfigs/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.ReusableConfig( + name="name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.ReusableConfig.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_reusable_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ReusableConfig) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_get_reusable_config_rest_required_fields( + request_type=service.GetReusableConfigRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_reusable_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_reusable_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ReusableConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.ReusableConfig.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_reusable_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_reusable_config_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_reusable_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_reusable_config_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_get_reusable_config", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, "pre_get_reusable_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetReusableConfigRequest.pb( + service.GetReusableConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.ReusableConfig.to_json( + resources.ReusableConfig() + ) + + request = service.GetReusableConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ReusableConfig() + + client.get_reusable_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_reusable_config_rest_bad_request( + transport: str = "rest", request_type=service.GetReusableConfigRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/reusableConfigs/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_reusable_config(request) + + +def test_get_reusable_config_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.ReusableConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/reusableConfigs/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.ReusableConfig.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_reusable_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{name=projects/*/locations/*/reusableConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_reusable_config_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_reusable_config( + service.GetReusableConfigRequest(), + name="name_value", + ) + + +def test_get_reusable_config_rest_error(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListReusableConfigsRequest, + dict, + ], +) +def test_list_reusable_configs_rest(request_type): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListReusableConfigsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListReusableConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_reusable_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReusableConfigsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_reusable_configs_rest_required_fields( + request_type=service.ListReusableConfigsRequest, +): + transport_class = transports.CertificateAuthorityServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_reusable_configs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_reusable_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListReusableConfigsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListReusableConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_reusable_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_reusable_configs_rest_unset_required_fields(): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_reusable_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_reusable_configs_rest_interceptors(null_interceptor): + transport = transports.CertificateAuthorityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CertificateAuthorityServiceRestInterceptor(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "post_list_reusable_configs", + ) as post, mock.patch.object( + transports.CertificateAuthorityServiceRestInterceptor, + "pre_list_reusable_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListReusableConfigsRequest.pb( + service.ListReusableConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListReusableConfigsResponse.to_json( + service.ListReusableConfigsResponse() + ) + + request = service.ListReusableConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListReusableConfigsResponse() + + client.list_reusable_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_reusable_configs_rest_bad_request( + transport: str = "rest", request_type=service.ListReusableConfigsRequest +): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_reusable_configs(request) + + +def test_list_reusable_configs_rest_flattened(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListReusableConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListReusableConfigsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_reusable_configs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta1/{parent=projects/*/locations/*}/reusableConfigs" + % client.transport._host, + args[1], + ) + + +def test_list_reusable_configs_rest_flattened_error(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_reusable_configs( + service.ListReusableConfigsRequest(), + parent="parent_value", + ) + + +def test_list_reusable_configs_rest_pager(transport: str = "rest"): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListReusableConfigsResponse( + reusable_configs=[ + resources.ReusableConfig(), + resources.ReusableConfig(), + resources.ReusableConfig(), + ], + next_page_token="abc", + ), + service.ListReusableConfigsResponse( + reusable_configs=[], + next_page_token="def", + ), + service.ListReusableConfigsResponse( + reusable_configs=[ + resources.ReusableConfig(), + ], + next_page_token="ghi", + ), + service.ListReusableConfigsResponse( + reusable_configs=[ + resources.ReusableConfig(), + resources.ReusableConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListReusableConfigsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_reusable_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ReusableConfig) for i in results) + + pages = list(client.list_reusable_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CertificateAuthorityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CertificateAuthorityServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CertificateAuthorityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CertificateAuthorityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CertificateAuthorityServiceGrpcTransport, + transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + transports.CertificateAuthorityServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CertificateAuthorityServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CertificateAuthorityServiceGrpcTransport, + ) + + +def test_certificate_authority_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CertificateAuthorityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_certificate_authority_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.security.privateca_v1beta1.services.certificate_authority_service.transports.CertificateAuthorityServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CertificateAuthorityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly # raise NotImplementedError. methods = ( "create_certificate", @@ -6800,6 +13971,7 @@ def test_certificate_authority_service_transport_auth_adc(transport_class): [ transports.CertificateAuthorityServiceGrpcTransport, transports.CertificateAuthorityServiceGrpcAsyncIOTransport, + transports.CertificateAuthorityServiceRestTransport, ], ) def test_certificate_authority_service_transport_auth_gdch_credentials(transport_class): @@ -6904,11 +14076,40 @@ def test_certificate_authority_service_grpc_transport_client_cert_source_for_mtl ) +def test_certificate_authority_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CertificateAuthorityServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_certificate_authority_service_rest_lro_client(): + client = CertificateAuthorityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_certificate_authority_service_host_no_port(transport_name): @@ -6919,7 +14120,11 @@ def test_certificate_authority_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("privateca.googleapis.com:443") + assert client.transport._host == ( + "privateca.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com" + ) @pytest.mark.parametrize( @@ -6927,6 +14132,7 @@ def test_certificate_authority_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_certificate_authority_service_host_with_port(transport_name): @@ -6937,7 +14143,92 @@ def test_certificate_authority_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("privateca.googleapis.com:8000") + assert client.transport._host == ( + "privateca.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://privateca.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_certificate_authority_service_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CertificateAuthorityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CertificateAuthorityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_certificate._session + session2 = client2.transport.create_certificate._session + assert session1 != session2 + session1 = client1.transport.get_certificate._session + session2 = client2.transport.get_certificate._session + assert session1 != session2 + session1 = client1.transport.list_certificates._session + session2 = client2.transport.list_certificates._session + assert session1 != session2 + session1 = client1.transport.revoke_certificate._session + session2 = client2.transport.revoke_certificate._session + assert session1 != session2 + session1 = client1.transport.update_certificate._session + session2 = client2.transport.update_certificate._session + assert session1 != session2 + session1 = client1.transport.activate_certificate_authority._session + session2 = client2.transport.activate_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.create_certificate_authority._session + session2 = client2.transport.create_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.disable_certificate_authority._session + session2 = client2.transport.disable_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.enable_certificate_authority._session + session2 = client2.transport.enable_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.fetch_certificate_authority_csr._session + session2 = client2.transport.fetch_certificate_authority_csr._session + assert session1 != session2 + session1 = client1.transport.get_certificate_authority._session + session2 = client2.transport.get_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.list_certificate_authorities._session + session2 = client2.transport.list_certificate_authorities._session + assert session1 != session2 + session1 = client1.transport.restore_certificate_authority._session + session2 = client2.transport.restore_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.schedule_delete_certificate_authority._session + session2 = client2.transport.schedule_delete_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.update_certificate_authority._session + session2 = client2.transport.update_certificate_authority._session + assert session1 != session2 + session1 = client1.transport.get_certificate_revocation_list._session + session2 = client2.transport.get_certificate_revocation_list._session + assert session1 != session2 + session1 = client1.transport.list_certificate_revocation_lists._session + session2 = client2.transport.list_certificate_revocation_lists._session + assert session1 != session2 + session1 = client1.transport.update_certificate_revocation_list._session + session2 = client2.transport.update_certificate_revocation_list._session + assert session1 != session2 + session1 = client1.transport.get_reusable_config._session + session2 = client2.transport.get_reusable_config._session + assert session1 != session2 + session1 = client1.transport.list_reusable_configs._session + session2 = client2.transport.list_reusable_configs._session + assert session1 != session2 def test_certificate_authority_service_grpc_transport_channel(): @@ -7366,6 +14657,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -7383,6 +14675,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: From 3b3bf779e87301507a10b22cd95838e7b1249407 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 6 Mar 2023 11:44:11 -0800 Subject: [PATCH 9/9] chore(main): release 1.7.0 (#341) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ google/cloud/security/privateca/gapic_version.py | 2 +- google/cloud/security/privateca_v1/gapic_version.py | 2 +- .../security/privateca_v1beta1/gapic_version.py | 2 +- ...metadata_google.cloud.security.privateca.v1.json | 2 +- ...ata_google.cloud.security.privateca.v1beta1.json | 2 +- 7 files changed, 19 insertions(+), 6 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 093be7e..64e0684 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.6.1" + ".": "1.7.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index ed7be85..e3efa52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [1.7.0](https://github.com/googleapis/python-security-private-ca/compare/v1.6.1...v1.7.0) (2023-03-06) + + +### Features + +* Add X.509 Name Constraints support ([423615c](https://github.com/googleapis/python-security-private-ca/commit/423615cc7b1c4b893e062e86e780e021475a7d0c)) +* Enable "rest" transport in Python for services supporting numeric enums ([423615c](https://github.com/googleapis/python-security-private-ca/commit/423615cc7b1c4b893e062e86e780e021475a7d0c)) + + +### Bug Fixes + +* Add service_yaml parameters to privateca_py_gapic ([423615c](https://github.com/googleapis/python-security-private-ca/commit/423615cc7b1c4b893e062e86e780e021475a7d0c)) + ## [1.6.1](https://github.com/googleapis/python-security-private-ca/compare/v1.6.0...v1.6.1) (2023-01-20) diff --git a/google/cloud/security/privateca/gapic_version.py b/google/cloud/security/privateca/gapic_version.py index b4028ab..f033c61 100644 --- a/google/cloud/security/privateca/gapic_version.py +++ b/google/cloud/security/privateca/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.6.1" # {x-release-please-version} +__version__ = "1.7.0" # {x-release-please-version} diff --git a/google/cloud/security/privateca_v1/gapic_version.py b/google/cloud/security/privateca_v1/gapic_version.py index b4028ab..f033c61 100644 --- a/google/cloud/security/privateca_v1/gapic_version.py +++ b/google/cloud/security/privateca_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.6.1" # {x-release-please-version} +__version__ = "1.7.0" # {x-release-please-version} diff --git a/google/cloud/security/privateca_v1beta1/gapic_version.py b/google/cloud/security/privateca_v1beta1/gapic_version.py index b4028ab..f033c61 100644 --- a/google/cloud/security/privateca_v1beta1/gapic_version.py +++ b/google/cloud/security/privateca_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.6.1" # {x-release-please-version} +__version__ = "1.7.0" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json index 2ae53b3..6da4a98 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-private-ca", - "version": "0.1.0" + "version": "1.7.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json index d9af1f5..3c7679b 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-private-ca", - "version": "0.1.0" + "version": "1.7.0" }, "snippets": [ {